首页 > 解决方案 > 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 %} 语句中将它们转换为字符串,但我一直失败

标签: pythondjango

解决方案


如果你想为每个区域显示 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外键关系


推荐阅读