python - 使用相关表的外键从模板中检索数据
问题描述
我正在尝试从与派生类的外键连接的模板级别检索数据。但它不起作用。
楷模:
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 %}
如何从模板的学生表中检索学生数据?
解决方案
推荐阅读
- html - 用于将照片从桌面添加到 html 代码的 Img src 不起作用
- ios - 在 iOS 设备上打开 .html 文件
- python - Twitter Streaming API 过滤器 - 按位置过滤 出现错误 - 按工作过滤器正常工作
- r - 如何更改 geom_sf 中的 alpha?
- c++ - 增加类指针数组
- android - 安卓 | 注册一次后不会出现注册表
- angular - Angular 7 spyon 不能在单元测试中工作?
- kubernetes - 如何在open shift中更改PVC的访问方式
- typo3 - 如何为高级功能注册模块
- php - 在php中填充购物车的项目数