如何检查Django模板中是否存在多对多关系?
在本代码示例中,“teachs_for”是将执行者模型与学校模型关联的多对多字段的名称。我只想在表演者和教师模型之间至少存在一种关系的情况下包含此特定块 以下是我的非工作代码:如何检查Django模板中是否存在多对多关系?,django,django-models,Django,Django Models,在本代码示例中,“teachs_for”是将执行者模型与学校模型关联的多对多字段的名称。我只想在表演者和教师模型之间至少存在一种关系的情况下包含此特定块 以下是我的非工作代码: {% if performer.teaches_for.exists %} <h3>{{performer.first_name}} teaches at these schools...</h3> <ul> {% for school in performer.teache
{% 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.teachs\u for.all.exists%}
如果没有学校,performer.teachs\u 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 %}
{performer.teachers\u for.all%}
{%if-forloop.first%}
{{performer.first{u name}}在这些学校任教……
{%endif%}
{%if-forloop.last}
{%endif%}
{%endfor%}
如果我从问题的右边剪下并粘贴
{% 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 %}