简体   繁体   English

Django如何使用注释计算百分比?

[英]Django how to compute the Percentage using annotate?

I want to compute the total average per grading categories and multiply it by given number using annotate我想计算每个评分类别的总平均值,并使用 annotate 将其乘以给定的数字

this is my views.py这是我的 views.py

from django.db.models import F
gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(grading_Period = period).filter(Subjects = subject).filter\
        (Grading_Categories__in = cate.values_list('id')).values('Grading_Categories').annotate( average_grade = Avg * F('Grading_Categories__PercentageWeight') / 100)

this is my models.py这是我的models.py

class gradingCategories(models.Model):
    CategoryName = models.CharField(max_length=500, null=True)
    PercentageWeight = models.FloatField()


class studentsEnrolledSubjectsGrade(models.Model):
    GradeLevel = models.ForeignKey(EducationLevel, related_name='grade', on_delete=models.CASCADE,
                                   null=True, blank=True)
    Subjects = models.ForeignKey(Subject, related_name='subject', on_delete=models.CASCADE, null=True)
    Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='student',
                                                    on_delete=models.CASCADE, null=True)
    Grading_Categories = models.ForeignKey(gradingCategories, related_name='category', on_delete=models.CASCADE,
                                           null=True, blank=True)
    grading_Period = models.ForeignKey(gradingPeriod, related_name='period', on_delete=models.CASCADE,
                                       null=True, blank=True)
    _dates  = models.CharField(max_length=255,null=True, blank=True)
    Grade = models.FloatField(null=True, blank=True)

For more info:欲了解更多信息:

For example the average of Quiz(Grading categories) is 80 and it will multiply with 15(PercentageWeight)例如测验(评分类别)的平均值是 80,它将乘以 15(百分比权重)

Total = 80(Grading_Categories) * 15(PercentageWeight) total=total / 100 Total = 80(Grading_Categories) * 15(PercentageWeight) total=total / 100

The result must be 12结果必须是 12

You can do this using F Expresisons您可以使用F 表达式执行此操作

From the Docs:从文档:

Reporter.objects.all().update(stories_filed=F('stories_filed') + 1)

So your example would be something like:所以你的例子是这样的:

studentsEnrolledSubjectsGrade.objects.all().annotate(grade_percent=(.8 * F('Grading_Categories')) * (.15 * F('PercentageWeight') / 100)

(as a side note, it is django/python standards to use UpperCaseCamelCase for class names, and snake_case for field names. So StudentsEnrolledSubjectsGrade, and grading_categories) check out Pep-8 for the details) (作为旁注,使用 UpperCaseCamelCase 作为类名,并使用 snake_case 作为字段名是 django/python 标准。因此 StudentsEnrolledSubjectsGrade 和 grading_categories)查看Pep-8了解详细信息)

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

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