Skip to content

Instantly share code, notes, and snippets.

@mentix02
Last active November 29, 2022 19:10
Show Gist options
  • Save mentix02/f1d545243b7eb37f7d033fc0735ec868 to your computer and use it in GitHub Desktop.
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.
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)
@mentix02
Copy link
Author

mentix02 commented Nov 8, 2018

Never mind. I got a better solution -

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)""".splitlines()

print("\n".join(sorted(fields, key=len)))

I feel dumb now.

@mentix02
Copy link
Author

Just use isort or black, dumbass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment