Django模板中的多对多

时间:2010-09-19 20:29:54

标签: django django-templates many-to-many

这是我在forloop中的模板标签

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

我想将数字1更改为forloop.counter。这是可能的吗?

喜欢:

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

它不能像那样工作,但是有办法做到这一点吗?

2 个答案:

答案 0 :(得分:8)

这没有意义。您应该遍历查询集本身。

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

答案 1 :(得分:4)

由于@ Daniel的答案不能满足你,我想你可能想尝试编写一个自定义过滤器。这是草稿:

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

您可以在模板中使用它,如下所示:

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