使用 Django 模板标签访问字典中的列表

时间:2021-03-19 07:12:34

标签: django for-loop django-templates

有点卡在如何访问字典中的列表值上。

我尝试了以下答案无济于事:

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

我如何获得这样的值?

1 个答案:

答案 0 :(得分:1)

您应该对视图中的数据进行预处理:

checkoutList = [
    {'id': id, 'title': title, 'location': location, 'imageurl': imageurl, 'url': url}
    for id, title, location, imageurl, url in zip(
        checkoutList['id'],
        checkoutList['title'],
        checkoutList['location'],
        checkoutList['imageurl'],
        checkoutList['url']
    )
]

然后你可以用:

{% for record in checkoutList %}
    {% for key, value in record.items %}
        {{key}} {{value}}
    {% endfor %}
{% endfor %}