问题
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}]>
and same goes to the rest of the students.
I would like to display it like :
Annie 2
Benny 3
Charlie 4
My view:
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)
My template:
{% 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
Thank you in advance.
回答1:
The below should return a quryset with student names and marks. Two separate queries should not be needed.
students = MarkAtt.objects.values('studName').annotate(mark=Sum('attendance'))
If studName
is a ForeignKey
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>
回答2:
You are overcomplicating things. Given the following simple context:
students = MarkAtt.objects.values('studName').annotate(mark=Sum('attendance'))
context = {
'students' : students,
}
you can do in the template:
{% for student in students %}
<p>{{student.studName}}</p> <p> {{ student.mark}}</p>
{% endfor %}
来源:https://stackoverflow.com/questions/58008040/display-sum-per-user-elegantly-in-django