2

I want to calculate count of approved comments?

news_list = News.objects.all()\
    .annotate(
        comments_count=Count(
            'comments__id', 
            comments__status=COMMENT_STATUS_APPROVED
        )
    )

But the second condition of Count-function is not working. How to filter annotate-function

2
  • Filtering on annotations is not possible in Django. You will have to use custom SQL. This blog entry may be useful: timmyomahony.com/blog/filtering-annotations-django Commented Feb 15, 2016 at 10:58
  • @Leistungsabfall Thanks for this link! I was changed the my queryset to use extra-select. Commented Feb 15, 2016 at 11:32

1 Answer 1

2

There is a similar question on how to annotate a count with a condition with a detailed answer and explanation of the SQL.

You can do conditional aggregation, using the conditional expression Case. The example in the docs is shows operation on a single model, but you can use the normal methods for inter-model relationships. The following QuerySet should be what you're looking for-

class NewsQuerySet(models.QuerySet):
    def with_comment_counts(self):
        query = self
        query = query.annotate(
            comment_count=Sum(
                Case(When(comment__status=COMMENT_STATUS_APPROVED, then=1
                          default=0,
                          output_field=IntegerField())
            ),
        return query
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.