【发布时间】:2019-06-20 14:24:13
【问题描述】:
我正在尝试遍历不同的区域,然后显示属于该区域的项目
Zone 是一个模型,有一个名称和一个 ForeignKey。 Planche 是一个具有 Zone 作为 ForeignKey 的模型。
我正在遍历区域以显示每个区域。在该循环中,我正在循环所有 Planches,并且只想显示将 Zone 作为 ForeignKey 的那些。
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 %} 语句中将它们转换为字符串,但我一直失败
【问题讨论】: