【发布时间】:2021-06-16 14:39:19
【问题描述】:
有点卡在如何访问字典中的列表值。
我尝试了以下答案均无济于事:
Access Dictionary Value inside list in Django Template
Accessing items in lists within dictionary python
我正在通过我的 view.py 文件传递以下内容:
context = {'checkoutList': CheckoutList, 'cartItems': cartItems}
return render(request, 'posts/checkout.html', context)
我尝试访问的查询集是 Checkoutlist,如下所示:
{'id': [30, 6], 'title': ['Lorem Ipsum', 'another title'], 'location': ['多个位置', 'city2'], 'imageurl': ['/media/image/img.jpg', '/media/image/img.jpg'], 'url': ['/products/lorem-ipsum', '/products/another-title']}
我正在尝试访问 Checkout.html 页面中的列表值,但我不知道如何访问。目前我可以得到键和整个列表值,见下文:
{% for key, value in checkoutList.items %}
{{key}} {{value}}
{% endblock %}
这是返回键值和整个列表,而不是列表中的值。
id [30,6]
title ['Lorem Ipsum', 'another title']
etc..
我真正追求的是每个 for 循环列表中的值
first iteration
30 lorem ipsum multiple locations
second iteration
6 another title city2
等
我如何获得这样的值?
【问题讨论】:
-
你能显示代码你是如何创建Checkoutlist
-
这是正确的。
id是第一个键,[30,6]是第一个对应的值。你可以做一些丑陋的事情,比如添加一个forloop.counter,但创建字典“更合适”似乎更好?
标签: django for-loop django-templates