开发者

Django Many to Many in template

开发者 https://www.devze.com 2023-01-16 23:17 出处:网络
This is my template tag in a forloop {{ product.feature_set.all.1.value }} i want to change the number 1 to the forloop.counter. is this posible?

This is my template tag in a forloop

{{ product.feature_set.all.1.value }}

i want to change the number 1 to the forloop.counter. is this posible?

like:

{{
product.feature_set.all.forloop.counter.value
}}

It does not work like that, but is th开发者_如何转开发ere a way to do this?


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

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


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

精彩评论

暂无评论...
验证码 换一张
取 消