[Solved]-Nested loop in Django template

17👍

You can use backwards relationships.

{% for item in ingrcat %}
<h2>{{ item.name }}</h2>
<ul>
    {% for ingr in item.ingredience_set.all %}
    <li><a href="#" id="i{{ ingr.id }}">{{ ingr.name }}</a></li>
    {% endfor %}
</ul>
{% endfor %}

See documentation:

https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

👤Fozzle

1👍

Do get_queryset on obj.manytomanyfield

{% for item in ingrcat %}
<h2>{{ item.name }}</h2>
<ul>
    {% for ingr in item.ingredients.get_queryset %}
    <li><a href="#" id="i{{ ingr.id }}">{{ ingr.name }}</a></li>
    {% endfor %}
</ul>
{% endfor %}
👤7guyo

Leave a comment