2024-04-26 13:48:35 发布
网友
我想计算已批准评论的数量?你知道吗
news_list = News.objects.all()\ .annotate( comments_count=Count( 'comments__id', comments__status=COMMENT_STATUS_APPROVED ) )
但是Count函数的第二个条件不起作用。如何过滤注解函数
在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
在how to annotate a count with a condition上有一个类似的问题,详细地回答和解释了SQL。你知道吗
您可以使用conditional expression Case执行conditional aggregation。文档中的示例显示了对单个模型的操作,但您可以使用模型间关系的常规方法。以下查询集应该是您要查找的-
相关问题 更多 >
编程相关推荐