任何想法如何做到这一点?
您应该使用
凝集(doc):
:from django.db.models import Avg
p = Property.objects.get(...)
stars_average = list(p.rating_set.aggregate(Avg('stars')).values())[0]
您可以使用Aggregate()
和
antotate()()平均通过属性中的模型和属性中的恒星,如下所示。 *我需要使用Rating
与order_by('pk')
一起使用annotate()
,否则值以降序打印:
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)
然后,下面的这些输出在控制台上:{'stars__avg': 3.7}
{'stars__avg': 3.2}
{'stars__avg': 3.6}
{'stars__avg': 4.0}
{'stars__avg': 3.2}
{'stars__avg': 3.6}
{'stars__avg': 4.0}
3.2
3.6
4.0
,您可以将默认键
stars__avg
stars列更改为
starsAvg
列,如下所示:
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
then,然后更改默认键,如下所示:
{'starsAvg': 3.7}
{'starsAvg': 3.2}
{'starsAvg': 3.6}
{'starsAvg': 4.0}
{'starsAvg': 3.2}
{'starsAvg': 3.6}
{'starsAvg': 4.0}
3.2
3.6
4.0