Django - 如何在模板“for”循环中执行元组拆包 [英] Django - How to do tuple unpacking in a template 'for' loop
问题描述
在我的views.py中,我正在构建一个两元组列表,其中元组中的第二个项目是另一个列表,如下所示:
[Product_Type_1,[product_1,product_2],
Product_Type_2,[product_3,product_4]]
在简单的老Python中,我可以像下列那样迭代列表:
for product_type,products in列表:
打印product_type
产品中的产品:
打印产品
我似乎在Django模板中做同样的事情:
{%for product_type,product_list%
print product_type
{%for product in products%}
print product
{%endfor%}
{%endfor%}
我从Django收到此错误:
而渲染:zip参数#2必须支持迭代
当然,有一些HTML标记在模板中,而不是打印语句。 Django模板语言中是否支持元组拆包?还是我这样做错了?所有我想要做的是显示一个简单的对象层次结构 - 有几种产品类型,每种都有几个产品(在models.py中,Product具有Product_type的外键,一个简单的一对多关系)。 p>
显然,我对Django来说是新手,所以任何输入都将不胜感激。
如果你构建你的数据,那么最好的,如{注意''''''''可以交换'['和']',一个是元组,一个用于列表}
[(Product_Type_1,(product_1,product_2)),
(Product_Type_2,(product_3,product_4))]
并使模板执行此操作:
code> {%for product_type,product_type_list%}中的产品
{{product_type}}
{%for product in products%}
{{product}}
{ %endfor%}
{%endfor%}
元组/列表的方式为unpa cked in for循环是基于列表迭代器返回的项目。
每次迭代只返回一个项目。第一次循环,Product_Type_1,第二个你的产品列表...
In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this:
[ Product_Type_1, [ product_1, product_2 ],
Product_Type_2, [ product_3, product_4 ]]
In plain old Python, I could iteration the list like this:
for product_type, products in list:
print product_type
for product in products:
print product
I can't seem to do the same thing in my Django template:
{% for product_type, products in product_list %}
print product_type
{% for product in products %}
print product
{% endfor %}
{% endfor %}
I get this error from Django:
Caught an exception while rendering: zip argument #2 must support iteration
Of course, there is some HTML markup in the template, not print statements. Is tuple unpacking not supported in the Django template language? Or am I going about this the wrong way? All I am trying to do is display a simple hierarchy of objects - there are several product types, each with several products (in models.py, Product has a foreign key to Product_type, a simple one-to-many relationship).
Obviously, I am quite new to Django, so any input would be appreciated.
it would be best if you construct your data like {note the '(' and ')' can be exchanged for '[' and ']' repectively, one being for tuples, one for lists}
[ (Product_Type_1, ( product_1, product_2 )),
(Product_Type_2, ( product_3, product_4 )) ]
and have the template do this:
{% for product_type, products in product_type_list %}
{{ product_type }}
{% for product in products %}
{{ product }}
{% endfor %}
{% endfor %}
the way tuples/lists are unpacked in for loops is based on the item returned by the list iterator. each iteration only one item was returned. the first time around the loop, Product_Type_1, the second your list of products...
这篇关于Django - 如何在模板“for”循环中执行元组拆包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!