首页 > 解决方案 > 使用相关表的外键从模板中检索数据

问题描述

我正在尝试从与派生类的外键连接的模板级别检索数据。但它不起作用。

楷模:

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 %}

如何从模板的学生表中检索学生数据?

标签: pythondjangodjango-modelsdjango-templatesdjango-views

解决方案


推荐阅读