python - Django模板,如果它们的id等于父循环名称,则循环遍历项目
问题描述
我正在尝试遍历不同的区域,然后显示属于该区域的项目
Zone 是一个模型,有一个名字和一个 ForeignKey。Planche 是具有 Zone 作为 ForeignKey 的模型。
我正在遍历区域以显示每个区域。在那个循环中,我正在循环所有 Planches,并且只想显示那些将 Zone 作为 ForeignKey 的 Planches。
class Zones(models.Model):
name = models.CharField(max_length=30)
genre = models.ForeignKey(ZoneTypes, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Planche(models.Model):
pzone = models.ForeignKey(Zones, on_delete=models.CASCADE)
ref = models.CharField(max_length=5, default="1")
length = models.IntegerField()
width = models.IntegerField()
orientation = models.CharField(max_length=30)
def __str__(self):
return self.ref
模板
<div>
<h1><a href="/">My list of planches</a></h1>
</div>
{% for z in zones %}
<div>
<h2><a href="/zone/{{ z.name }}">Zone name: {{ z.name }}</a></h2>
{% for p in planches %}
{% if p.pzone == z.name }
<h1><a href="planche/{{ planche.ref }}">Ref: {{ p.ref }}</a></h1>
<p>Length: {{ p.length }} - Width: {{ p.width }}</p>
<p>Orientation: {{ p.orientation }}
{% endif %}
{% endfor %}
</div>
{% endfor %}
{% if p.pzone = z.name %} 返回 False,如果我只显示它们,它们都返回相同的字符串 {{ p.pzone }} 和 {{ z.name }} 但我猜它们不一样数据类型。我尝试在 {% with %} 语句中将它们转换为字符串,但我一直失败
解决方案
如果你想为每个区域显示 Planches,你可以像这样编写第二个循环:
<div>
<h1><a href="/">My list of planches</a></h1>
</div>
{% for z in zones %}
<div>
<h2><a href="/zone/{{ z.name }}">Zone name: {{ z.name }}</a></h2>
{% for p in z.planche_set.all %}
<h1><a href="planche/{{ planche.ref }}">Ref: {{ p.ref }}</a></h1>
<p>Length: {{ p.length }} - Width: {{ p.width }}</p>
<p>Orientation: {{ p.orientation }}
{% endif %}
{% endfor %}
</div>
{% endfor %}
这是另一篇文章中的示例:模板中的Django外键关系
推荐阅读
- c++ - 在 CPU 机器中多线程处理更大的 c++ 程序
- typescript - Typescript - 在具有条件返回类型的函数中返回特定类型
- mysql - MySQL 5.7 vs 5.6:起初索引使用错误,但几周后“自动”修复
- java - 访问引用实体字段的正确方法
- javascript - 如何在所有服务器之间共享身份验证信息?
- python-3.x - python简单帮助(NameError:名称未定义)
- ios - SwiftUI List - 禁用特定行的移动?
- docusignapi - docusign api 选项卡标签通配符匹配文档在哪里
- python-3.x - Python 避免使用非阻塞写入命名管道的部分写入
- javascript - window.open 找不到 html 文件