Skip to content Skip to sidebar Skip to footer

Define Sorting Key On Django Model

I have two Django models, in which the one refers to the other. I want to be able to sort the second model based on the first. I think the code example below illustrates best what

Solution 1:

The ordering Meta field only controls how records are sorted in database queries. sorted is a Python function and completely unrelated to this.

To make Record instance sortable in Python, you can give them a __lt__ method:

def__lt__(self, other):
    returnself.code < other.code

Now Python can sort them, and your error will be gone. But it's better to let the database do it, so don't use sorted at all:

defget_sorted_submodels(self):
    returnself.submodels.order_by('record__code')

Edit: to do it after your edit, I'd change the methods like so (import cached_property from django.utils.decorators):

@cached_property
def record(self):
    return Record.objects.get(uuid=self.record_uuid)

@staticmethod
def key_sorting(obj):
    return (obj.record.code, obj.code)

Solution 2:

If you only want to use this ordering in some contexts you can specify it wherever you select your records. This should work: Submodel.objects.all().order_by('submodels', 'record__name').

If you need to use this custom ordering in a lot of different places you can look into making a custom Model Manager.

Post a Comment for "Define Sorting Key On Django Model"