在我的views.py中,我正在构建一个双元组列表,其中元组中的第二项是另一个列表,如下所示:
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 ]]
在普通的旧 Python 中,我可以像这样迭代列表:
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
我似乎无法在我的 Django 模板中做同样的事情:
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 %}
我从 Django 收到此错误:
I get this error from Django:
渲染时遇到异常:zip 参数 #2 必须支持迭代
当然,模板中有一些 HTML 标记,而不是打印语句.Django 模板语言不支持元组解包吗?还是我以错误的方式解决这个问题?我要做的只是显示一个简单的对象层次结构 - 有几种产品类型,每种都有几个产品(在 models.py 中,Product 有一个 Product_type 的外键,一个简单的一对多关系).
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).
显然,我对 Django 还是很陌生,因此我们将不胜感激.
Obviously, I am quite new to Django, so any input would be appreciated.
最好像{note the '(' and ')' can be exchangely for '[' and ']' 这样构建数据,一个用于元组,一个用于列表}
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 )) ]
并让模板执行此操作:
{% for product_type, products in product_type_list %}
{{ product_type }}
{% for product in products %}
{{ product }}
{% endfor %}
{% endfor %}
元组/列表在 for 循环中解包的方式基于列表迭代器返回的项目.每次迭代只返回一项.第一次循环,Product_Type_1,第二次你的产品列表......
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"循环中进行元组解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!