【发布时间】:2020-05-20 17:10:58
【问题描述】:
我有这些模型:
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 访问这些计数的总和。
我不知道怎么做。
【问题讨论】:
标签: python django postgresql django-orm django-annotate