【问题标题】:Accessing lists inside a dictionary with Django Template tags使用 Django 模板标签访问字典中的列表
【发布时间】: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


【解决方案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 %}

【讨论】:

    猜你喜欢
    • 2016-02-29
    • 2015-08-18
    • 1970-01-01
    • 2018-09-11
    • 2021-10-17
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    相关资源
    最近更新 更多