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