[Django]-Django ORM How I can get average value

2👍

You must try with F() functions. I think this could solve your problem

https://docs.djangoproject.com/en/1.7/ref/models/queries/#f-expressions

Affiliate.objects.get(pk=2).testimonials_set.all().aggregate(Avg(F('rating_stability') + F('rating_sup')))

1👍

You could add a default=0 value to your model fields which you want to aggregate:

rating_sup = models.IntegerField(choices=RATING, max_length=1, blank=True, default=0)
rating_stability = models.IntegerField(choices=RATING, max_length=1, blank=True, default=0)
rating_trust = models.IntegerField(choices=RATING, max_length=1, blank=True, default=0)

and then you can aggregate all thre fields using Avg

Affiliate.testimonials_set.all().aggregate(avr=Avg(F('rating_trust') + F('rating_sup') + F('rating_stability'))).order_by('avr')
👤doru

Leave a comment