[英]Django - How to SUM the related Model field with Filter in Annotate?
[英]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
有很多Products
和RoutingCategory
有很多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.