1

我有这些模型:

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)
)

其中平均评级是每个机构。有任何想法吗?

4

2 回答 2

1
Feedback.objects.aggregate(avg_rating=Avg('rating'))
于 2017-10-10T10:50:16.200 回答
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)))
于 2017-10-10T11:59:50.073 回答