【发布时间】:2018-02-24 23:30:40
【问题描述】:
假设我有以下模型结构:
Parent():
Child():
parent = ForeignKey(Parent)
GrandChild():
child = ForeignKey(Child)
state = BooleanField()
num = FloatField()
我正在尝试从父 ViewSet 恢复以下内容:
- 孩子的数量。
- 当 'state' 为 True 时,'num' 字段的 SUM。
我可以做到以下几点:
queryset = Parent.objects\
.annotate(child_count=Count('child'))\
.annotate(sum_total=Sum('child__grandchild__num'))
这给了我 (1) 但不是 (2) 它给了我所有孙子的总和。如何在确保所有 Parent 对象仍在 QuerySet 中的同时适当地过滤孙子对象?
【问题讨论】:
标签: django django-models django-queryset django-aggregation django-annotate