ScotchAndSoda
ScotchAndSoda

Reputation: 4171

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 !

Upvotes: 3

Views: 2899

Answers (3)

riodpp
riodpp

Reputation: 85

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

Upvotes: 1

Alasdair
Alasdair

Reputation: 308799

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.

Upvotes: 5

esse
esse

Reputation: 5539

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.

Upvotes: 2

Related Questions