我有这些模型:
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)
)
其中平均评级是每个机构。有任何想法吗?