假设我有以下模型结构:
Parent():
Child():
parent = ForeignKey(Parent)
GrandChild():
child = ForeignKey(Child)
state = BooleanField()
num = FloatField()
我试图从父
ViewSet
,恢复如下:我可以执行以下操作:
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/