【问题标题】:annotate sum of annotated values in related model标注相关模型中标注值的总和
【发布时间】:2020-05-20 17:10:58
【问题描述】:

我有这些模型:

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

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

class RoutingCategory(MPTTModel):
   pass

所以InputCategory 有很多ProductsRoutingCategory 有很多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


    【解决方案1】:

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

    不过你不需要那个,你可以在这里Count相关产品:

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

    【讨论】:

    • 也许我还有另一个(类似的)问题。我在问题的底部添加了一个编辑。请随时检查,谢谢。
    猜你喜欢
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多