如何在 django-queryset 中过滤注释数据



我想计算已批准评论的数量?

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

但是计数函数的第二个条件不起作用。如何过滤注释函数

关于如何用带有详细答案和 SQL 解释的条件注释计数,有一个类似的问题。

您可以使用条件表达式 Case 执行条件聚合。文档中的示例显示了对单个模型的操作,但您可以使用常规方法处理模型间关系。以下查询集应该是您要查找的内容-

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

最新更新