如何从 Django 视图中字典的'for'循环中检索索引号



我正在尝试获取{% for p in mydict_1 %}的索引号,以便在另一个dict上使用该索引来获取值。我想用p作为索引号。如何在Django视图中做到这一点?两个列表中的数据都对应于序列中的索引。

mylist_1 = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}, {'itemCode': 'AP01', 'price': 1.2}] #list of dict
mylist_2 = [{'prop': 'val000'}, {'prop': 'val008'}, {'prop': 'val009'}] #list of dict
{% for p in mylist_1 %}
<tr>
<td><a>{{p.itemCode}}</a></td>
<td><a>{{p.price}}</a></td>
#Want to use p's index number to get value of that index from mylist_2
<td><a>{{mylist_2.[p].prop}}</a></td> #How to do this correctly? Expecting val000 for index 0
</tr>
{% endfor %}

您没有。Django的模板语言故意限制这一点,以防止人们在模板中编写业务逻辑。您可以将带有zip(…)[python-doc]的字典传递到模板:

def my_view(request):
# …
context = {
# …,
'mydicts': zip(mydict_1, mydict_2)
}
return render(request, 'some-template.html', context)

在模板中,然后使用进行迭代

{% forp, q in mydicts%}
{{ p.itemCode }}
{{ p.price }}
{{ q.prop }}
{% endfor %}

最新更新