gpt4 book ai didi

django - 如何从带注释的 Django 查询中过滤/排除非事件评论?

转载 作者:行者123 更新时间:2023-12-04 21:26:58 25 4
gpt4 key购买 nike

我正在使用 object_list快速列出一组文章的通用 View 。每篇文章都附有评论。查询使用对 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=Falseis_removed=True .如何从计数中排除任何不活跃的评论?

最佳答案

documentation for aggregations解释了如何做到这一点。您需要使用 filter条款,确保将其放在 annotate 之后条款:

Article.objects.annotate(comment_count=Count('comments')).filter(
comment__is_public=True, comment__is_removed=False
).order_by('-comment_count')

关于django - 如何从带注释的 Django 查询中过滤/排除非事件评论?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1838592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com