我有以下模型:
class Product(..):
category = ForeignKey('InputCategory...
class InputCategory(MPTTModel):
route_to = ForeignKey('RoutingCategory...
class RoutingCategory(MPTTModel):
pass
因此InputCategory
有许多Products
,而RoutingCategory
有许多InputCategory
对象。
我可以为product_count
注释InputCategory
:
InputCategory.objects.annotate(product_count=Count('products'))
但是我需要将product_count
注释到RoutingCategory
上。
我该怎么做?
我尝试为Manager
修改InputCategory
,并执行以下操作:
RoutingCategory.objects.annotate(product_count=Sum('input_categories__product_count'))
但是它说:FieldError: Unsupported lookup 'product_count' for AutoField or join on the field not permitted.
很明显,我应该覆盖相关的Manager。
你知道怎么做吗?
编辑
@Willem Van Onsem提出了有效的答案:
from django.db.models import Count
RoutingCategory.objects.annotate(
product_count=Count('input_categories__products')
)
但是我也注释了product_cumulative_count
,它计算了自我和InputCategory
的所有祖先的乘积。我也想从RoutingCategory
访问这个总数。
我不知道怎么办。
答案 0 :(得分:1)
首先,与此有关的一个问题是Django不会不使用.objects
管理器来访问相关模型。但是,即使这样做,它也不起作用(很好)。 SQL不允许这样的多级GROUP BY,或者至少不允许不首先进行查询,然后在另一个查询中使用该结果。
但是您仍然不需要这样做,您可以在此处Count
关联产品:
from django.db.models import Count
RoutingCategory.objects.annotate(
product_count=Count('input_categories__products')
)