如何从带注释的 Django 查询中过滤/排除非活动注释?
我正在使用 object_list
通用视图快速列出一组文章。每篇文章都附有评论。该查询使用注释来 Count()
评论数量,然后 order_by()
该注释数字。
'queryset': Article.objects.annotate(comment_count=Count('comments')).order_by('-comment_count'),
注释是 django.contrib.comments 框架的一部分,并通过通用关系附加到模型。我已经在我的文章模型中添加了显式反向查找:
class Article(models.Models):
...
comments = generic.GenericRelation(Comment, content_type_field='content_type', object_id_field='object_pk')
问题是,这会计算“不活跃”评论;具有 is_public=False
或 is_removed=True
的。如何排除所有非活跃评论的计数?
I'm using the object_list
generic view to quickly list a set of Articles. Each Article has comments attached to it. The query uses an annotation to Count()
the number of comments and then order_by()
that annotated number.
'queryset': Article.objects.annotate(comment_count=Count('comments')).order_by('-comment_count'),
The comments are part of the django.contrib.comments
framework and are attached to the model via a Generic Relationship. I've added an explicit reverse lookup to my Article model:
class Article(models.Models):
...
comments = generic.GenericRelation(Comment, content_type_field='content_type', object_id_field='object_pk')
The problem is, this counts "inactive" comments; ones that have is_public=False
or is_removed=True
. How can I exclude any inactive comments from being counted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
聚合文档< /a> 解释了如何执行此操作。您需要使用
filter
子句,并确保将其放在annotate
子句之后:The documentation for aggregations explains how to do this. You need to use a
filter
clause, making sure you put it after theannotate
clause: