views:

119

answers:

1

I'm using the object_list generic view to quickly list a set of Articles. Each Article has comments attached to it. The query uses an annotation to Count() the number of comments and then order_by() that annotated number.

'queryset': Article.objects.annotate(comment_count=Count('comments')).order_by('-comment_count'),

The comments are part of the django.contrib.comments framework and are attached to the model via a Generic Relationship. I've added an explicit reverse lookup to my Article model:

class Article(models.Models):
   ...
   comments = generic.GenericRelation(Comment, content_type_field='content_type', object_id_field='object_pk')

The problem is, this counts "inactive" comments; ones that have is_public=False or is_removed=True. How can I exclude any inactive comments from being counted?

+1  A: 

The documentation for aggregations explains how to do this. You need to use a filter clause, making sure you put it after the annotate clause:

Article.objects.annotate(comment_count=Count('comments')).filter(
     comment__is_public=True, comment__is_removed=False
).order_by('-comment_count')
Daniel Roseman
wouldn't that filter articles based on whether or not they have public/removed comments?
Jiaaro
It seems to have worked but I'm going to do some investigating to make sure what Jim said isn't happening.
Soviut
One side effect I did notice is that it ONLY returns articles that have comments, those without are excluded.
Soviut