[英]Django - Count related with filter
I have a model called Article
and I have a model called Comment
which has a foreignkey to Article
. 我有一个名为
Article
的模型,并且有一个名为Comment
的模型,该模型具有Article
。 I want to count from a Article
queryset all comments in that queryset. 我想从
Article
集中计算该queryset中的所有注释。
Example: I have a queryset with 5 articles and every article has 3 comments except for one. 示例:我有一个包含5篇文章的查询集,每篇文章都有3条评论,除了一条。 -> This should return 12.
->这应该返回12。
Another example: One article has 3 comments and another one has 5 and other articles have no comments. 另一个示例:一篇文章有3条评论,另一篇文章有5条评论,其他文章没有评论。 -> This should return 8.
->这应该返回8。
I tried it with: 我尝试了:
Article.objects.all().annotate(comments_count=Count("comment", filter=Q(is_deleted=False))).comments_count
You should .aggregate(..)
[Django-doc] here, not [Django-doc] . annotate(..)
您应该在
.aggregate(..)
[Django-doc] ,而不是 [Django-doc] 。 Annotating adds a value to each item in the original queryset. annotate(..)
注释会为原始查询集中的每个项目添加一个值。 We can thus generate a query like:
因此,我们可以生成如下查询:
Article.objects.
aggregate(
comments_count=Count('comment', filter=Q(comment__is_deleted=False))
)
['comments_count']
Although it might be simpler to use the Comment
model itself here, like: 尽管在这里使用
Comment
模型本身可能更简单,例如:
Comment.objects.filter(
is_deleted=False,
article__in=my_article_qs
)
.count()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.