from django.db.models import Avg
# Average the stars in "Rating" model
print(Rating.objects.aggregate(Avg('stars')))
print()
# Average the stars in "Rating" model property by property
for obj in Property.objects.all():
print(
Rating.objects.filter(property=obj)
.aggregate(Avg('stars'))
)
print()
# Average the stars in "Rating" model property by property
for obj in Property.objects.all():
print(obj.rating_set.aggregate(Avg('stars')))
print()
# Average the stars in "Rating" model property by property
qs = Property.objects.annotate(Avg('rating__stars')).order_by('pk')
for obj in qs:
print(obj.rating__stars__avg)
from django.db.models import Avg
# Average the stars in "Rating" model
print(Rating.objects.aggregate(starsAvg=Avg('stars')))
# ↑ Here
print()
# Average the stars in "Rating" model property by property
for obj in Property.objects.all():
print(
Rating.objects.filter(property=obj)
.aggregate(starsAvg=Avg('stars'))
) # ↑ Here
print()
# Average the stars in "Rating" model property by property
for obj in Property.objects.all():
print(obj.rating_set.aggregate(starsAvg=Avg('stars')))
# ↑ Here
print()
# Average the stars in "Rating" model property by property
qs = Property.objects.annotate(starsAvg=Avg('rating__stars')).order_by('pk')
for obj in qs: # ↑ Here
print(obj.starsAvg)
# ↑ Here
2条答案
按热度按时间u4vypkhs1#
您应该使用Aggregation(doc):
但我对我的例子有点不确定。
jtjikinw2#
您可以将aggregate()和annotate()与Avg()一起使用,以按属性计算
Rating
模型中的星级平均值,如下所示。* 我需要将order_by('pk')
与annotate()
一起使用,否则值将按降序打印:然后,在控制台上输出以下内容:
并且,您可以将stars列的默认键
stars__avg
更改为starsAvg
,如下所示:然后,默认密钥更改如下: