gpt4 book ai didi

Django 在模型字段上注释 Avg

转载 作者:行者123 更新时间:2023-11-29 13:17:40 24 4
gpt4 key购买 nike

我有这些模型:

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

每个机构的平均评分。有什么想法吗?

最佳答案

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

关于Django 在模型字段上注释 Avg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46664815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com