2

,总价值比方说,我有以下的模型结构:Django的注释模型基于查询

Parent(): 

Child(): 
parent = ForeignKey(Parent) 

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

我从父ViewSet努力,恢复如下:

  1. 的儿童人数。
  2. '状态'为True时'num'字段的和。

我可以做到以下几点:

queryset = Parent.objects\ 
    .annotate(child_count=Count('child'))\ 
    .annotate(sum_total=Sum('child__grandchild__num')) 

这给了我(1),但不是(2)它给了我为所有孙子的总和。我应该如何筛选孙辈,同时确保所有Parent对象仍在QuerySet中?

回答

1

尝试注释

queryset = Parent.objects.filter(child__grandchild__state=True')\ 
    .annotate(child_count=Count('child'))\ 
    .annotate(sum_total=Sum('child__grandchild__num')) 
您正在使用着Django的版本
+0

这将工作,但我需要确保我有所有的父对象。对不起,我会编辑最初的问题。 – Eric

+0

@Eric您将从此获得父对象queryset。 –

+0

如果特定的父母没有GrandChild,该怎么办? – Eric

0

之前使用过滤器?如果支持版本,您也可以使用子查询。

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

您可以通过聚合查询来优化这一点。

+0

子查询可能是我需要遵循的路线,但您的答案不正确。我在找一笔总和,而不是一个伯爵。 2.我没有名为'Event'的模型。 3.字段'num'是一个FloatField,而不是一个IntegerField。 – Eric