Sort queryset by a generic foreign key (django)?

2019-06-26 06:21发布

问题:

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 ?

回答1:

The way you found in the blog post linked in your question is the way I'd do it (and, indeed, pretty much the way I did it in one of my own projects earlier this week)