模型.py
class Testimonials(models.Model):
RATING = (
(1,'Очень плохо'),
(2,'Плохо'),
(3,'Средне'),
(4,'Хорошо'),
(5,'Очень хорошо'),
)
EXP = (
(1, 'Не указан'),
(2, 'Один день'),
(3, 'Одна неделя'),
(4, 'Один месяц'),
(5, 'Более года'),
)
user = models.OneToOneField(User)
publish = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
testimonial = models.TextField(max_length=1000, null=True, blank=True)
rating_sup = models.IntegerField(choices=RATING, max_length=1, null=True, blank=True)
rating_stability = models.IntegerField(choices=RATING, max_length=1, null=True, blank=True)
rating_trust = models.IntegerField(choices=RATING, max_length=1, null=True, blank=True)
experience = models.IntegerField(choices=EXP, max_length=1, default=1, blank=True)
affiliate = models.ForeignKey(Affiliate, null=True, blank=True)
offer = models.ForeignKey(Offer, null=True, blank=True)
我的查询集是:
Affiliate.objects.get(pk=2).testimonials_set.all().aggregate(Avg('rating_trust'), Avg('rating_sup'), Avg('rating_stability'))
结果:
{'rating_stability__avg': 3.0, 'rating_trust__avg': None, 'rating_sup__avg': 4.0}
我如何获得 3 个值的平均值 ((3+4)/2=3.5)
最佳答案
您必须尝试使用 F() 函数。我认为这可以解决您的问题
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')))
关于sql - Django ORM 如何获得平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35652128/