在Django中优雅地显示每个用户的总和 [英] display sum per user elegantly in django
问题描述
试图显示每个学生的最终成绩。但是,它不仅显示总和的结果,还显示了一大堆查询集:例如:
trying to display the final mark per student. But instead of just showing the result of sum , it displays a chunk of query set: for example:
Annie <QuerySet [{'studName': None, 'attendance__sum': 3}, {'studName': 1, 'attendance__sum': 2}, {'studName': 2, 'attendance__sum': 1}]>
其余学生也是如此。
我想显示为:
Annie 2
Benny 3
Charlie 4
Charlie 4
我的观点:
def attStudName(request):
studentName = MarkAtt.objects.all()
mark = MarkAtt.objects.values('studName').annotate(Sum('attendance'))
context = {
'studentName' : studentName,
'mark' : mark
}
return render(request,'show-name.html',context)
我的模板:
{% for y in mark %}
{% for x in studentName %}
<p>{{x.studName}}</p> <p> {{mark}}</p>
{% endfor %}
{% endfor %}
如何显示每个带有自己标记的学生姓名?以及如何在没有
How do i display each student name with their own mark accordingly? And how do i display the mark without the
编辑的情况下显示标记:
Edited:
Model.py:
class Namelist(models.Model):
name = models.CharField(max_length=100)
program = models.CharField(max_length=10)
year = models.IntegerField(default=1)
studType = models.CharField(max_length=15)
courseType = models.CharField(max_length=15)
nationality = models.CharField(max_length=20)
VMSAcc = models.CharField(max_length=30)
classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True)
class MarkAtt(models.Model):
studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None)
classGrp = models.ForeignKey(GroupInfo, on_delete=models.SET_NULL, null=True)
currentDate = models.DateField(default=now())
week = models.IntegerField(default=1)
attendance = models.IntegerField(default=100) #1 is present
谢谢。
推荐答案
以下内容应返回带有学生姓名和分数的查询集。
The below should return a queryset with student names and marks. Two separate queries should not be needed.
students = MarkAtt.objects.values('studName').annotate(mark=Sum('attendance'))
如果 studName
是外键,执行此操作 .values('studName__name')
If studName
is a foreign key, do this .values('studName__name')
然后在您的上下文中,只需添加:
Then in your context you can just add:
context = {
students = students
}
然后您可以在模板中遍历学生
并将数据显示为:
You can then loop through students
in you template and display data as:
<p>{{x.studName}}</p> <p> {{x.mark}}</p>
这篇关于在Django中优雅地显示每个用户的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!