Myzel394
Myzel394

Reputation: 1317

Django - Count related with filter

I have a model called Article and I have a model called Comment which has a foreignkey to Article. I want to count from a Article queryset all comments in that queryset.

Example: I have a queryset with 5 articles and every article has 3 comments except for one. -> This should return 12.

Another example: One article has 3 comments and another one has 5 and other articles have no comments. -> This should return 8.

I tried it with:

Article.objects.all().annotate(comments_count=Count("comment", filter=Q(is_deleted=False))).comments_count

Upvotes: 2

Views: 223

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

You should .aggregate(..) [Django-doc] here, not annotate(..) [Django-doc]. Annotating adds a value to each item in the original queryset. We can thus generate a query like:

Article.objects.aggregate(
    comments_count=Count('comment', filter=Q(comment__is_deleted=False))
)['comments_count']

Although it might be simpler to use the Comment model itself here, like:

Comment.objects.filter(
    is_deleted=False,
    article__in=my_article_qs
).count()

Upvotes: 4

Related Questions