简体   繁体   English

Django 平均模型输入

[英]Django averaging models inputs

I am able to take the average of the model inputs helpfulness, pedagogy, and easiness as seen in my models.py.我可以在我的 models.py 中看到 model 输入有用性、教学法和易用性的平均值。 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?如何在 Django 中执行此操作?

models.py:模型.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?也许?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM