[Django]-Django Many to Many in template

10👍

This doesn’t make sense. You should be looping through the queryset itself.

{% for feature in product.feature_set.all %}
    {{ feature }}
{% endfor %}

4👍

Since @Daniel’s answer doesn’t satisfy you, I thought you might want to try writing a custom filter. Here is a rough draft:

@register.filter
def custom_m2m(queryset, forloop_counter):
    return queryset[forloop_counter].value

You can use it in your template like this:

{% for ... %}
    {{ product.feature_set.all|custom_m2m:forloop.counter }}
{% endfor %}

Leave a comment