试图在python Django中用不同的键映射两个相应的值

2024-04-19 11:31:01 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的django项目中,我尝试映射以下内容:

views.py

context = {'name': [a, b, c], 'price': [x, y, z], 'date': [1, 2, 3]}

return render(request, 'index.html', context)

在myindex.html中:

{% for value in context %}
    <tr>
        <td>{{ value.name }}</td>
        <td>{{ value.price }}</td>
        <td>{{ value.date}}</td>
    </tr>
{% endfor %}

我的目标是通过以下方式获得表格:

name | price | date
a    |   x   | 1
b    |   y   | 2
c    |   z   | 3

我尝试过不同的方法,但到目前为止,我只能得到一个专栏。我是Python新手。任何帮助都是非常困难的


1条回答
网友
1楼 · 发布于 2024-04-19 11:31:01

您应该以相反的方式执行此操作:创建一个可编辑的词典(例如列表),例如使用^{} [Python-doc]

data = {'name': [a, b, c], 'price': [x, y, z], 'date': [1, 2, 3]}
new_data = [
    {'name': n, 'price': p, 'date': d}
    for n, p, d in zip(data['name'], data['price'], data['date'])
]

return render(request, 'index.html', {'data': new_data})

在模板中,然后可以使用以下方法渲染:

{% for row in data %}
    <tr>
        <td>{{ row.name }}</td>
        <td>{{ row.price }}</td>
        <td>{{ row.date }}</td>
    </tr>
{% endfor %}

相关问题 更多 >