如何检查Django模板中是否存在多对多关系?

时间:2019-07-23 14:01:45

标签: django django-models

在此代码示例中,“ teaches_for”是将Performer模型与School模型关联的多对多字段的名称。我只想在表演者和教师模型之间至少存在一种关系的情况下才包含此特定块。

这是我无法使用的代码:

{% if performer.teaches_for.exists %}
<h3>{{performer.first_name}} teaches at these schools...</h3>

<ul>
    {% for school in performer.teaches_for.all %}
    <li><a href="/schools/{{school.id}}">{{ school.name }}</a></li>
    {%  endfor %}
</ul>

{% endif %}

错误的行是{% if performer.teaches_for.exists %}。如果至少存在一种关系,我将如何替换为True,否则将其替换为False?

Performer模型中的相关字段如下:

    teaches_for = models.ManyToManyField(
        School,
        verbose_name="Teaches at this school",
        blank=True,
        related_name="teachers",
    )

2 个答案:

答案 0 :(得分:2)

尝试{% if performer.teaches_for.all.exists %}

答案 1 :(得分:1)

如果没有学校,{% for school in performer.teaches_for.all %}循环将执行零次。因此,通过在forloop.first上进行测试,将标头放入循环中。

{% for school in performer.teaches_for.all %}
    {% if forloop.first %}
       <h3>{{performer.first_name}} teaches at these schools...</h3><ul>
    {% endif %}

    <li><a href="/schools/{{school.id}}">{{ school.name }}</a></li>

   {% if forloop.last}</ul> {%endif%}
{%  endfor %}

如果我已经从右边的问题中剪切并粘贴了。