我正在尝试循环不同的区域,然后显示属于该区域的项目
Zone是一个模型,有一个名称和一个ForeignKey。 Planche 是一个以 Zone 作为外键的模型。
我正在循环区域以显示每个区域。在该循环中,我循环所有 Planches,并且只想显示那些将 Zone 作为外键的 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
Template
<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 %} 语句中的字符串,但我一直失败
我假设您想显示每个区域的所有木板。您可以使用related_name
on the ForeignKey
访问引用当前对象的项目。您没有在那里设置任何相关名称,因此它是默认名称:planche_set
.
<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 }}
{% endfor %}
</div>
{% endfor %}
请注意,该方法将执行 N+1 次查询(一次用于选择您的区域,然后每个区域一次查询以检索每个区域的 Planches),除非您添加prefetch_related('planche')
在您选择的视图中zones
.
参考:
- 关于向后关系的官方文档 https://docs.djangoproject.com/en/stable/topics/db/queries/#backwards-related-objects
- Django 中的“related_name”有什么用? https://stackoverflow.com/questions/2642613/what-is-related-name-used-for-in-django
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)