Django在模型字段上注释平均值

时间:2017-10-10 10:47:14

标签: django postgresql django-queryset django-aggregation django-annotate

我有这些模特:

class Agency(models.Model):
    pass


class User(models.Model):
    agency = models.ForeignKey(Agency)


class Feedback(models.Model):
    rating = models.DecimalField()
    user = models.ForeignKey(User)

我希望用所有评级的平均值来注释查询集。我希望这可行:

Feedback.objects.annotate(avg_rating=Avg('rating')).values('rating', 'avg_rating')

但它只输出:

<QuerySet [{'rating': 0.8, 'avg_rating': 0.8}, {'rating': 0.2, 'avg_rating': 0.2}, {'rating': 0.6, 'avg_rating': 0.6}, {'rating': 1.0, 'avg_rating': 1.0}, {'rating': 0.4, 'avg_rating': 0.4}]>

正如您所看到的,平均值应为3.0。我哪里错了?

为了清楚起见,我试图做这样的事情:

agencies = Agency.objects.annotate(
    avg_rating=Coalesce(Subquery(
        Feedback.objects.filter(user__agency_id=OuterRef('pk'))
        .values('rating')
        .annotate(avg_rating=Avg('rating', output_field=DecimalField()))
        .values('avg_rating')
    ), 0)
)

其中平均评级是每个代理商。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

Feedback.objects.aggregate(avg_rating=Avg('rating'))

答案 1 :(得分:0)

也许试试这个:

agencies = Agency.objects.annotate(
avg_rating=Coalesce(Subquery(
    Feedback.objects.values('user__agency')
    .annotate(avg_rating=Avg('rating', output_field=DecimalField()))
    .values('avg_rating')
), 0)))