Salim Fadhley
Salim Fadhley

Reputation: 8245

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

In this code example, "teaches_for" is the name of a many-to-many field that relates a Performer model to a School model. I want to include this particular block only if at least one relationship between a Performer and a Teacher model exists.

Here's my non-working code:

{% 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 %}

The line that's wrong is {% if performer.teaches_for.exists %}. What can I replace it with which will be True if at least one relationship exists, but False otherwise?

The relevant field in my Performer model looks like this:

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

Upvotes: 4

Views: 1895

Answers (3)

Hagyn
Hagyn

Reputation: 962

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

Upvotes: 8

Damir Nafikov
Damir Nafikov

Reputation: 332

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

Upvotes: 2

nigel222
nigel222

Reputation: 8222

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.

Upvotes: 1

Related Questions