Sort queryset by a generic foreign key (django)?

Posted by thornomad on Stack Overflow See other posts from Stack Overflow or by thornomad
Published on 2010-05-29T13:20:42Z Indexed on 2010/05/29 13:22 UTC
Read the original article Hit count: 198

Filed under:
|

I am using Django's comment framework which utilizes generic foreign keys.

Question: How do I sort a given model's queryset by their comment count using the generic foreign key lookup?

Reading the django docs on the subject it says one needs to calculate them not using the aggregation API:

Django's database aggregation API doesn't work with a GenericRelation. [...] For now, if you need aggregates on generic relations, you'll need to calculate them without using the aggregation API.

The only way I can think of, though, would be to iterate through my queryset, generate a list with content_type and object_id's for each item, then run a second queryset on the Comment model filtering by this list of content_type and object_id ... sort the objects by the count, then re-create a new queryset in this order by pulling the content_object for each comment ...

This just seems wrong and I'm not even sure how to pull it off.

Ideas? Someone must have done this before.

I found this post online but it requires me handwriting SQL -- is that really necessary ?

© Stack Overflow or respective owner

Related posts about django

Related posts about foreign-keys