I am able to take the average of the model inputs helpfulness, pedagogy, and easiness as seen in my models.py. However, I also want to take the average of the averages of these three ratings and name it as "overall". How do I do this in Django?
models.py:
from django.db import models
from django.db.models import Avg
class Prof(models.Model):
name = models.CharField(max_length=100, unique=True)
association = models.CharField(max_length=50)
def avg_ratings(self):
return self.ratings.aggregate(
Avg('helpfulness'),
Avg('pedagogy'),
Avg('easiness'),
)
def __str__(self):
return self.name
class Rating(models.Model):
helpfulness_choices = (
(1, 'Very Unhelpful'),
(2, 'Unhelpful'),
(3, 'Moderate'),
(4, 'Helpful'),
(5, 'Very Helpful'),
)
pedagogy_choices = (
(1, 'Very Low Pedagogy'),
(2, 'Low Pedagogy'),
(3, 'Moderate'),
(4, 'High Pedagogy'),
(5, 'Very High Pedagogy'),
)
easiness_choices = {
(1, 'Very Difficult'),
(2, 'Difficult'),
(3, 'Moderate'),
(4, 'Easy'),
(5, 'Very Easy'),
}
name = models.ForeignKey(Prof, on_delete=models.CASCADE, related_name="ratings")
subject = models.CharField(max_length=10)
helpfulness = models.IntegerField(choices=helpfulness_choices)
pedagogy = models.IntegerField(choices=pedagogy_choices)
easiness = models.IntegerField(choices=easiness_choices)
comment = models.TextField()
def __str__(self):
return str(self.name)
template:
{% with avg_ratings=prof.avg_ratings %}
Helpfulness: {{ avg_ratings.helpfulness__avg }} <br>
Pedagogy: {{ avg_ratings.pedagogy__avg }} <br>
Easiness: {{ avg_ratings.easiness__avg }}
{% endwith %}
return self.ratings.annotate(
help_avg=Avg('helpfulness'),
ped_avg = Avg('pedagogy'),
ease_avg = Avg('easiness'),
).annotate(overall=(F('help_avg')+F('ped_avg')+F('ease_avg'))/3).values('help_avg','ped_avg','ease_avg','overall')
I think? maybe?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.