开发者

Django: Order by number of comments issue

开发者 https://www.devze.com 2023-02-08 17:37 出处:网络
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 comme

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 开发者_Python百科
BY num_comments DESC LIMIT 4


Think I found the answer: Django Snippet

0

精彩评论

暂无评论...
验证码 换一张
取 消