django 使用基于查询的聚合值注释模型

标签 django django-models django-queryset django-aggregation django-annotate

假设我有以下模型结构:

Parent():

Child():
parent = ForeignKey(Parent)

GrandChild():
child = ForeignKey(Child)
state = BooleanField()
num = FloatField()

我试图从父 ViewSet ,恢复如下:
  • child 的数量。
  • 'state' 为 True 时的 'num' 字段的总和。

  • 我可以执行以下操作:
    queryset = Parent.objects\
        .annotate(child_count=Count('child'))\
        .annotate(sum_total=Sum('child__grandchild__num'))
    

    这给了我 (1) 但不是 (2) 它给了我所有孙子的总和。如何在确保我拥有所有 Parent 的同时适本地过滤孙子对象仍然在 QuerySet 中?

    最佳答案

    您使用的是哪个版本的 django?如果支持版本,您也可以使用子查询。

    from django.db.models import OuterRef, Subquery
    
    Parent.objects
    .annotate(child_count=Count('child'))
    .annotate(
        grandchild_count_for_state_true=Subquery(
            GrandChild.objects.filter(
                state=True,
                child=OuterRef('pk')
            ).values('parent')
            .annotate(cnt=Sum('child__grandchild__num'))
            .values('cnt'),
            num=models.IntegerField()
        )
    )
    

    您可以通过聚合查询来优化它。

    关于django 使用基于查询的聚合值注释模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46245222/

    相关文章:

    python - 生菜、 Django 的背景

    python - 如何在 django 的 url 中传递特殊字符

    python - 如何在 Django ORM 中进行通配符搜索以替换单个字符 (_)?

    python - 尝试在 django 中读取文本文件

    javascript - 如何在 django 模板中设置变量(使用 set 标签)?

    python - Django:只清理特定的模型字段?

    django - 我是否在 django 中以错误的方式重写了模型上的保存方法?

    django - 为什么 django manage.pysyncdb 无法在我的开发服务器上创建新列?

    python - Django 按组保留一个元素,然后在此查询集上使用属性

    python - 如何从 Django 中的 RawQuerySet 中检索值?