Last active
November 29, 2022 19:10
-
-
Save mentix02/f1d545243b7eb37f7d033fc0735ec868 to your computer and use it in GitHub Desktop.
when developing a django model, I was cleaning up my code when I saw how messy the model fields look. So I implemented a sorting function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import OrderedDict | |
def sort_model_fields(fields): | |
print("BEFORE\n") | |
print(fields) | |
# creating a dictionary with key as length of string and value as the string itself | |
dict_fields = {} | |
list_fields = fields.splitlines() | |
for field in list_fields: | |
dict_fields[len(field)] = field | |
# sorting fields | |
ordered_fields = OrderedDict(sorted(dict_fields.items())) | |
print("\nAFTER\n") | |
for field in ordered_fields: | |
print(ordered_fields[field]) | |
# how my models.py coded looked | |
fields = """title = models.CharField(max_length=50) | |
content = models.TextField() | |
description = models.TextField(blank=True, null=True) | |
thumbnail = models.ImageField(upload_to='post_thumbnails') | |
draft = models.BooleanField(default=False) | |
slug = models.SlugField(blank=True) | |
author = models.CharField(max_length=30, default='mentix02', blank=True) | |
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)""" | |
sort_model_fields(fields) |
Just use isort or black, dumbass.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Never mind. I got a better solution -
I feel dumb now.