[Django]-How do I check if a many-to-many relationship exists in a Django template?

2👍

In django 3.2.4 Hagyn’s answer needs correction: {% if performer.teaches_for.all.exists() %}
And now it works as needed

6👍

Try {% if performer.teaches_for.all.exists %}.

👤Hagyn

1👍

The {% for school in performer.teaches_for.all %} loop will execute zero times if there are no schools. So put the header into the loop with a test on 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 %}

If I’ve cut-and-pasted from the question right.

Leave a comment