我正在尝试从与外键连接的模板级别检索数据 派生类。但不起作用。
型号:
class School(models.Model):
name = models.CharField(max_length = 256)
principal = models.CharField(max_length = 256)
location = models.CharField(max_length = 256)
class Student(models.Model):
name = models.CharField(max_length = 256)
age = models.PositiveIntegerField()
school = models.ForeignKey(School, related_name='students', on_delete = models.CASCADE)
观看次数:
class SchoolListView(ListView):
context_object_name = 'schools'
model = models.School
template_name = 'basic_app/School_list.html'
class SchoolDetailView(ListView):
context_object_name = 'school_detail'
model = models.School
template_name = "basic_app/School_dtl.html"
模板
<div class="jumbotron">
<h1>Welcome to School Detail page</h1>
<h2>School Details:</h2>
<p>Name: {{ school_detail.name}} </p>
<p>Principal: {{ school_detail.principal}} </p>
<p>Location: {{ school_detail.location}} </p>
<h3> Students:</h3>
{% for student in school_detail.students.all %}
<p>{{ student.name }} who is {{ student.age }} years old.</p>
{% endfor %}
无法从模板的学生表中检索学生数据。