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 !
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With