这是我在for循环Django的多对多模板
{{ product.feature_set.all.1.value }}
我想1号更改为forloop.counter模板标签。这是可能的吗?
喜欢:
{{
product.feature_set.all.forloop.counter.value
}}
它不喜欢的工作,但有没有办法做到这一点?
这是我在for循环Django的多对多模板
{{ product.feature_set.all.1.value }}
我想1号更改为forloop.counter模板标签。这是可能的吗?
喜欢:
{{
product.feature_set.all.forloop.counter.value
}}
它不喜欢的工作,但有没有办法做到这一点?
这没有意义。你应该循环查询集本身。
{% for feature in product.feature_set.all %}
{{ feature }}
{% endfor %}
由于@丹尼尔的答案不满足你,我想你可能想尝试编写一个自定义过滤器。这是一个粗略的草稿:
@register.filter
def custom_m2m(queryset, forloop_counter):
return queryset[forloop_counter].value
你可以用它在你的模板是这样的:
{% for ... %}
{{ product.feature_set.all|custom_m2m:forloop.counter }}
{% endfor %}
这是我知道如何做到这一点的最好和唯一的方法。原因是product.feature_set.all.forloop.counter会尝试product.feature_set.all.forloop,并在尝试意识到这是不可能的时候停止尝试。 – Jake 2012-09-24 14:01:21
不,这不是我想要的。我知道你可以做到这一点。我想像我问的那样。有没有可能? – Harry 2010-09-19 21:29:23