[Django]-Order by a content object's value in Django

5👍

There isn’t going to be an elegant way to do this in the queryset. To do the sorting in SQL, you would have to join the MyModel table to every other table that content_type refers to.

You can sort in python, but note this requires one lookup per object.

queryset = list(MyModel.objects.all())
sorted_queryset = sorted(queryset, key=lambda x: x.content_object.counter)

If sorting on the counter field efficiently is really important to you, you may want to consider moving the counter field (or duplicating it) to MyModel.

2👍

In your Model you can define an inner Meta class and define your ordering.

class MyModel(models.Model):
    ...
    class Meta:
        ordering = ['counter']

Would have to test it, but I think that is a step in the right direction.

👤esse

1👍

you can use order_by attribute after select your object.

Mymodels.objects.all().order_by('name_field')

references : https://books.agiliq.com/projects/django-orm-cookbook/en/latest/asc_or_desc.html

👤riodpp

Leave a comment