views:

228

answers:

1

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  A: 

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)

stevejalim
Thanks - I gave it a try and it does work. Seemed excessive but that just may be the way it is. Now I need to try and figure out how I can limit this special queryset by a certain time frame (for example, ordered by most comments in the last 24 hours). I will open another question for that one though.
thornomad
Because you're still working with querysets rather than raw SQL (ie, the extra() lets you use raq SQL but still keeps you in the world of h) you can either use annotate() to on the objects/rows you've narrowed the SELECT down to, or you can use another extra to write your own number-of-comments-counting query, depending on how your models are set up. HTH, Steve
stevejalim
Interesting - thanks. I just posted a new question (with code) to get some specific help for my scenario -- I went around and around on it yesterday and am just guessing at this point. Just need to solve that final part. See: http://stackoverflow.com/questions/2938519/sort-and-limit-queryset-by-comment-count-and-date-using-queryset-extra-django Thanks again! Very helpful.
thornomad