我想计算已批准评论的数量?
news_list = News.objects.all()\
.annotate(
comments_count=Count(
'comments__id',
comments__status=COMMENT_STATUS_APPROVED
)
)但是Count-function的第二个条件不起作用。如何过滤注解函数
发布于 2016-02-17 00:37:52
在how to annotate a count with a condition上也有类似的问题,提供了详细的答案和解释。
你可以使用 do conditional aggregation,使用conditional expression Case。文档中的示例显示了对单个模型的操作,但您可以使用常规方法处理模型之间的关系。下面的QuerySet应该是您要查找的内容-
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 queryhttps://stackoverflow.com/questions/35407420
复制相似问题