(Django)从值的注释中调用模板中的字段名称?

时间:2020-10-02 20:57:42

标签: python django django-queryset aggregation

我正在尝试建立学校管理系统,我想显示学生所参加的每门课程的总分(最终是字母成绩)。这是我的学生作业模型:

class StudentAssignment(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE)
    points_earned = models.IntegerField(blank=True, null=True)
    feedback = models.TextField(blank=True, null=True)

    def get_absolute_url(self):
        return reverse('assignments_all_students', args=[str(self.assignment.pk)])

在我看来,当学生点击其当前课程时:

@login_required
def my_courses(request):
    user = request.user
    student = Student.objects.filter(user=user).first()
    all_assignments = StudentAssignment.objects.filter(student=student)
    #This groups the assignments by each course, then divides it by total points to get a percentage
    all_scores = all_assignments.values('assignment__session_link').annotate(score=(Cast(Sum('points_earned'),
                                                 FloatField()) / Cast(Sum('assignment__total_points'),
                                                                      FloatField()) * 100)).exclude(points_earned=None)
    if student is None:
        return render(request, 'users/not_student.html')
    active_classes = student.enrolled_courses.all()
    if len(active_classes) == 0:
        return render(request, 'users/no_courses.html')
    context = {'classes': active_classes,
           'scores': all_scores}
    return render(request, 'users/my_courses.html', context)

现在的问题是我的“分数”上下文不再具有字段名称,因此我无法引用模板中的任何内容来显示课程标题,说明等内容。

是否有一种获取这些字段名称的方法,还是将一个字段添加到我的StudentAssignment上更好,该字段可以在老师给分数评分后进行百分比计算?

0 个答案:

没有答案