【问题标题】:How filter annotated data in django-queryset如何过滤 django-queryset 中的注释数据
【发布时间】:2023-03-30 22:27:01
【问题描述】:

我想计算批准的 cmets 的数量?

news_list = News.objects.all()\
    .annotate(
        comments_count=Count(
            'comments__id', 
            comments__status=COMMENT_STATUS_APPROVED
        )
    )

但计数功能的第二个条件不起作用。如何过滤annotate-function

【问题讨论】:

  • 在 Django 中无法过滤注释。您将不得不使用自定义 SQL。此博客条目可能有用:timmyomahony.com/blog/filtering-annotations-django
  • @Leistungsabfall 感谢您提供此链接!我已将我的查询集更改为使用额外选择。

标签: python django django-models django-queryset


【解决方案1】:

how to annotate a count with a condition上有一个类似的问题,有详细的回答和SQL的解释。

可以使用conditional expression Case 执行conditional aggregation。文档中的示例显示了对单个模型的操作,但您可以使用常规方法来处理模型间关系。以下 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 query

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-07
    • 2019-08-03
    • 1970-01-01
    • 2018-12-30
    • 2019-01-22
    • 2012-03-07
    • 2019-08-17
    • 2014-07-13
    相关资源
    最近更新 更多