簡體   English   中英

注釋相關模型中注釋值的總和

[英]annotate sum of annotated values in related model

我有這些模型:

class Product(..):
    category = ForeignKey('InputCategory...

class InputCategory(MPTTModel):
   route_to = ForeignKey('RoutingCategory...

class RoutingCategory(MPTTModel):
   pass

所以InputCategory有很多ProductsRoutingCategory有很多InputCategory對象。

我可以為InputCategory注釋product_count

InputCategory.objects.annotate(product_count=Count('products'))

但我需要將product_count注釋到RoutingCategory

我怎樣才能做到這一點?

我嘗試修改InputCategory Manager並執行以下操作:

RoutingCategory.objects.annotate(product_count=Sum('input_categories__product_count'))

但它說: FieldError: Unsupported lookup 'product_count' for AutoField or join on the field not permitted.

顯然我應該覆蓋相關的經理。

你知道怎么做嗎?

編輯

@Willem Van Onsem 提出了這個有效的答案:

from django.db.models import Count
RoutingCategory.objects.annotate(
    product_count=Count('input_categories__products')
)

但是我還注釋了product_cumulative_count ,它計算了InputCategory的 self 和所有祖先的InputCategory 我也想從RoutingCategory訪問這個計數的總和。

我無法弄清楚如何。

首先,這樣做的一個問題是 Django沒有使用.objects管理器來訪問相關模型。 但即使這樣做了,它也不會起作用(好吧)。 SQL 不允許這樣的多級 GROUP BY,或者至少在沒有首先進行查詢,然后在另一個查詢中使用該結果的情況下不允許。

但是無論如何您都不需要它,您可以在此處Count相關產品:

from django.db.models import Count

RoutingCategory.objects.annotate(
    product_count=Count('input_categories__products')
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM