如何在Django查询中过滤已注释的数据

2024-04-26 13:48:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算已批准评论的数量?你知道吗

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

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


Tags: 函数id数量objectsstatuscountcomment评论
1条回答
网友
1楼 · 发布于 2024-04-26 13:48:35

how to annotate a count with a condition上有一个类似的问题,详细地回答和解释了SQL。你知道吗

您可以使用conditional expression Case执行conditional aggregation。文档中的示例显示了对单个模型的操作,但您可以使用模型间关系的常规方法。以下查询集应该是您要查找的-

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

相关问题 更多 >