Django: Order by number of comments issue

325 views Asked by At

I'm trying to order a list of items in django by the number of comments they have. However, there seems to be an issue in that the Count function doesn't take into account the fact that django comments also uses a content_type_id to discern between comments for different objects!

This gives me a slight problem in that the comment counts for all objects are wrong using the standard methods; is there a 'nice' fix or do I need to drop back to raw sql?

Code to try and ge the correct ordering:

app_list = App.objects.filter(published=True)
.annotate(num_comments=Count('comments'))
.order_by('-num_comments')

Sample output from the query (note no mention of the content type id):

SELECT "apps_app"."id", "apps_app"."name", 
"apps_app"."description","apps_app"."author_name", "apps_app"."site_url", 
"apps_app"."source_url", "apps_app"."date_added", "apps_app"."date_modified", 
"apps_app"."published", "apps_app"."published_email_sent", "apps_app"."created_by_id", 
"apps_app"."rating_votes", "apps_app"."rating_score", COUNT("django_comments"."id") AS      
"num_comments" FROM "apps_app" LEFT OUTER JOIN "django_comments" ON ("apps_app"."id" = 
"django_comments"."object_pk") WHERE "apps_app"."published" = 1 GROUP BY 
"apps_app"."id", "apps_app"."name", "apps_app"."description", "apps_app"."author_name", 
"apps_app"."site_url", "apps_app"."source_url", "apps_app"."date_added", 
"apps_app"."date_modified", "apps_app"."published", "apps_app"."published_email_sent", 
"apps_app"."created_by_id", "apps_app"."rating_votes", "apps_app"."rating_score" ORDER 
BY num_comments DESC LIMIT 4
1

There are 1 answers

0
Paul On

Think I found the answer: Django Snippet