相关模型中带注释值的带注释之和

时间:2020-02-04 20:02:50

标签: python django postgresql django-orm django-annotate

我有以下模型:

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访问这个总数。

我不知道怎么办。

1 个答案:

答案 0 :(得分:1)

首先,与此有关的一个问题是Django不会使用.objects管理器来访问相关模型。但是,即使这样做,它也不起作用(很好)。 SQL不允许这样的多级GROUP BY,或者至少不允许不首先进行查询,然后在另一个查询中使用该结果。

但是您仍然不需要这样做,您可以在此处Count关联产品:

from django.db.models import Count

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