【问题标题】:How to filter/exclude inactive comments from my annotated Django query?如何从我的带注释的 Django 查询中过滤/排除非活动评论?
【发布时间】:2010-12-22 18:07:07
【问题描述】:

我正在使用object_list 通用视图快速列出一组文章。每篇文章都附有 cmets。该查询使用Count() cmets 数量的注释,然后使用order_by() 注释数字。

'queryset': Article.objects.annotate(comment_count=Count('comments')).order_by('-comment_count'),

cmets 是django.contrib.comments 框架的一部分,并通过通用关系附加到模型。我在我的文章模型中添加了显式反向查找:

class Article(models.Models):
   ...
   comments = generic.GenericRelation(Comment, content_type_field='content_type', object_id_field='object_pk')

问题是,这会计算“非活动”cmets;那些有is_public=Falseis_removed=True。如何排除任何不活动的 cmets?

【问题讨论】:

    标签: django django-models django-queryset django-managers generic-relationship


    【解决方案1】:

    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')
    

    【讨论】:

    • 那不是根据文章是否有公开/删除的 cmets 来过滤文章吗?
    • 它似乎奏效了,但我会做一些调查以确保 Jim 所说的没有发生。
    • 我注意到的一个副作用是它只返回有 cmets 的文章,没有的文章被排除在外。
    猜你喜欢
    • 2014-07-07
    • 2020-09-04
    • 2021-03-10
    • 2013-05-02
    • 2022-01-14
    • 2018-10-08
    • 2019-06-06
    • 1970-01-01
    • 2018-12-08
    相关资源
    最近更新 更多