Here's how I did it on a recent Django project:
from django.db import models
SomeClass(models.Model):
title = models.CharField()
@property
def alphabetical_title(self):
"""
Returns an alphabetical-friendly string of a title attribute.
"""
title = self.title
# A list of flags to check each `title` against.
starts_with_flags = [
'the ',
'an ',
'a '
]
# Check each flag to see if the title starts with one of it's contents.
for flag in starts_with_flags:
if title.lower().startswith(flag):
# If the title does indeed start with a flag, return the title with
# the flag appended to the end preceded by a comma.
return "%s, %s" % (title[len(flag):], title[:len(flag)-1])
else:
pass
# If the property did not return as a result of the previous for loop then just
# return the title.
return self.title
Since this is a property and not an actual column in the database I need to retrieve a QuerySet first and then sort it after the fact in a view. Here's how I did that:
from operator import attrgetter
from someapp.models import SomeClass
some_objects = SomeClass.objects.all()
sorted_objects = sorted(some_objects, key=attrgetter('alphabetical_title'), reverse=False)
I'm sure you've long since found a solution but I figured it might help to post it anyways as someone else in the future might run into this same problem.