我是Django的新手,我正在尝试创建一个网站来管理班级信息,例如学生及其统计信息。当我单击一个班级时,我可以看到该班级的详细信息以及该班级的学生。但是,我也希望获得每个学生的平均分数,但是我不知道如何从我的统计模型中检索数据。我尝试了select_related但没有用。预先谢谢你。
我想在Django中做到这一点
SELECT class.id, class.name, class.day_and_time, student.name, average(statistics.dictation_score), average(statistics.grammar_score)
FROM classes
INNER JOIN students on student_class = class.id
INNER JOIN statistics on student = student.id
WHERE class.id =(some number)
我的模型.py文件:
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")
我的观点.py文件:
class ClassesDetailView(DetailView):
stats = models.Students.objects.select_related('statistics')
context_object_name = "class_detail"
model = models.Classes
template_name = "classesapp/class_detail.html"