Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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",
    )
like image 625
Salim Fadhley Avatar asked Aug 31 '25 03:08

Salim Fadhley


1 Answers

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

Edit: In Django >3.2.4: {% if performer.teaches_for.all.exists() %} (thanks Damir Nafikov)

like image 118
Hagyn Avatar answered Sep 02 '25 22:09

Hagyn