Django注释子查询的聚合

时间:2020-02-07 13:23:58

标签: django django-orm django-aggregation django-annotate

所以我有三个模型

class Advert(BaseModel):
    company = models.ForeignKey(Company, on_delete=CASCADE, related_name="adverts")

class Company(BaseModel):
    name = models.CharField(max_length=50)

class OrderRating(BaseModel):
    reported_company = models.ForeignKey(Company, on_delete=CASCADE, related_name='ratings')
    rating = models.DecimalField(
        max_digits=2,
        decimal_places=1,
        validators=[MinValueValidator(1.0), MaxValueValidator(5.0)],
        help_text='Rating from 1.0 to 5.0.'
    )

当我这样做时,我试图获取与该公司相关的所有订单评分的平均值,并在Advert模型中添加注释:

 qs = Advert.objects.all().annotate(
        avg_rating=Subquery(
            OrderRating.objects.filter(
               reported_company=OuterRef('company')).aggregate(Avg("rating"))["rating__avg"]
            )
        )

我回来说

This queryset contains a reference to an outer query and may only be used in a subquery.'

不确定在OuterRef内致电Subquery时问题出在哪里。

1 个答案:

答案 0 :(得分:2)

根据我的经验Subqueries常常有些棘手,而且没有详细记录。当定义子查询的代码中出现错误时,它们往往会返回您收到的消息(实际上不是非常有用的消息)。

据我所知aggregateSubequeries中不起作用,您必须改用annotations。所以这应该工作:

qs = Advert.objects.all().annotate(
        avg_rating=Subquery(
            OrderRating.objects.filter(
               reported_company=OuterRef('company')).values('reported_company').annotate(av=Avg('rating')).values('av')
            )
        )