开发者

get average from set of objects in django

开发者 https://www.devze.com 2022-12-27 14:39 出处:网络
Hay, i have a simple rating system for a property. You give it a mark out of 5 (stars). The models are defined like this

Hay, i have a simple rating system for a property. You give it a mark out of 5 (stars). The models are defined like this

def Property(models.Model)
    # stuff here

def Rating(models.Model)
    property = models.ForeignKey(Property)
    stars = models.IntegerField()

What i want to do is get a property, find all the Rating objects,开发者_如何学Python collect them, then get the average 'stars' from them.

any ideas how to do this?


You should use Aggregation(doc):

from django.db.models import Avg

p = Property.objects.get(...)
stars_average = p.rating_set.aggregate(Avg('stars')).values()[0]

A little bit unsure about my example though.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号