Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by a content object's value in Django

I am looking for an elegant way to order a queryset by a specific content object's field.

class MyModel(models.Model):
    ...
    content_type    = models.ForeignKey(ContentType)
    object_pk       = models.TextField('object ID')
    content_object  = generic.GenericForeignKey('content_type', 'object_pk')

My content objects are various, but all of them have a 'counter' field

class OtherObject(models.Model):
    ...
    counter = models.PositiveIntegerField(default=0)
    ...

It would be nice I could query all my MyModel objects ordering them by the related object's counter value.

Thanks !

like image 740
ScotchAndSoda Avatar asked Mar 11 '26 23:03

ScotchAndSoda


2 Answers

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.

like image 118
Alasdair Avatar answered Mar 14 '26 13:03

Alasdair


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.

like image 31
esse Avatar answered Mar 14 '26 12:03

esse