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",
)
Try {% if performer.teaches_for.all.exists %}
.
Edit: In Django >3.2.4: {% if performer.teaches_for.all.exists() %} (thanks Damir Nafikov)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With