我想做以下事情,但我不知道该怎么做:
对于每个班级,请向我显示该班级中的所有学生,对于该班级的每个学生,请向我显示该学生的所有统计信息。
我的模型是:
class Classes(models.Model):
name = models.CharField(max_length=256)
day_and_time= models.CharField(max_length=256)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("classesapp:class_detail", kwargs={"pk": self.pk})
class Students(models.Model):
name = models.CharField(max_length=256)
student_class = models.ForeignKey(
Classes, related_name = 'students', on_delete=models.SET_NULL, null=True
)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("classesapp:student_detail", kwargs={"pk": self.pk})
class Statistics(models.Model):
student= models.ForeignKey(
Students, related_name='statistics', on_delete=models.CASCADE, null=True
)
date = models.DateField(blank=True, null=True)
dictation_score = models.FloatField()
writing_score = models.FloatField()
test_score = models.FloatField()
grammar_score = models.FloatField()
in_class_performance = models.FloatField()
class Meta:
ordering = ["-date"]
def get_absolute_url(self):
return reverse("classesapp:classes_list")
我的ClassesDetailView是:
class ClassesDetailView(DetailView):
queryset = models.Classes.objects.select_related('statistics')
context_object_name = "class_detail"
model = models.Classes
template_name = "classesapp/class_detail.html"
我知道我必须覆盖查询集,我尝试了select_relatad,但仍然找不到解决方案。 预先谢谢你!
答案 0 :(得分:0)
它将运行2个循环。根据您的模型,class
可以有很多students
,而student
可以有很多statistics
。
已更新:
result = []
for student in Students.objects.all():
student_data = {}
student_data['student_name'] = student.name
student_data['class_name'] = student.student_class.name
statistics_data = []
for statistics in student.statistics.all():
statistics_data.append({
'dictation_score': statistics.dictation_score,
'writing_score': statistics.writing_score,
'grammer_score': statistics.grammer_score,
'in_class_performance': statistics.in_class_performance
})
student_data['statistics_data'] = statistics_data
result.append(student_data)