Python Django//如何在模板中显示复杂的深度数据
Django 2.2// python 3.6//Python Django//如何在模板中显示复杂的深度数据,python,django,Python,Django,Django 2.2// python 3.6// 我用“列表”和“字典”的组合创建了一个上下文 数据结构如下所示 { "Mike":[ { "month":"2020-02", "consult_counts_total":2, "consult_counts_total_uid":2 }, { "month":"2020-01", "consult_c
我用“列表”和“字典”的组合创建了一个上下文 数据结构如下所示
{
"Mike":[
{
"month":"2020-02",
"consult_counts_total":2,
"consult_counts_total_uid":2
},
{
"month":"2020-01",
"consult_counts_total":4,
"consult_counts_total_uid":7
},
{
"month":"2019-12",
"consult_counts_total":6,
"consult_counts_total_uid":1
}
],
"Jaden":[
{
"month":"2020-02",
"consult_counts_total":8,
"consult_counts_total_uid":12
},
{
"month":"2020-01",
"consult_counts_total":23,
"consult_counts_total_uid":11
},
{
"month":"2019-12",
"consult_counts_total":2,
"consult_counts_total_uid":19
}
],
"Sarah":[
{
"month":"2020-02",
"consult_counts_total":2,
"consult_counts_total_uid":2
},
{
"month":"2020-01",
"consult_counts_total":4,
"consult_counts_total_uid":7
},
{
"month":"2019-12",
"consult_counts_total":6,
"consult_counts_total_uid":1
}
],
"John":[
{
"month":"2020-02",
"consult_counts_total":1,
"consult_counts_total_uid":0
},
{
"month":"2020-01",
"consult_counts_total":2,
"consult_counts_total_uid":7
},
{
"month":"2019-12",
"consult_counts_total":5,
"consult_counts_total_uid":1
}
]
}
我试图通过模板中的循环来显示这些数据
首先我试过了。它显示了很好的结果
{% for foo in context_data %}
<p>{{ foo }}</p>
{% endfor %}
# result
Mike
Jaden
Sarah
John
我怎样才能做到这一点呢?您只是在迭代键,应该使用项来迭代值
{% for key, values in context_data.items %}
<p class="big">This is {{ key }}'s months.</p>
{% for foo2 in values %}
<p class="small">{{ foo2.month }}</p>
{% endfor %}
<br>
{% endfor %}
{%用于键,上下文中的值\u data.items%}
这是{key}的月份
{值%%中的foo2为%1}
{{foo2.month}
{%endfor%}
{%endfor%}
您传递的上下文数据是什么?dict
,而不是json
数据信息。您在第二次尝试时有{{foo2.months}
,这是打字错误吗?当我在这里写问题的时候,应该是month
@chrisbyte,我想我打错了。“月”是正确的。@Felipe我用views.py中的list和dic创建了这些数据,并呈现到模板中。所以这不是json dataSaisiva//你让我知道了我不知道的事情。你告诉我的那个人的名字越来越好了。但我无法从“值”中获取数据,可能是因为它比“列表”更深一步。这应该怎么解决?哦哦。很好。非常感谢。
{% for foo in context_data %}
<p class="big">This is {{ foo }}'s months.</p>
{% for foo2 in foo %}
<p class="small">{{ foo2 }}</p>
{% endfor %}
<br>
{% endfor %}
# result
This is Mike's months.
M
i
k
e
This is Mike's months.
2020-02
2020-01
2019-12
This is Jaden's months.
2020-02
2020-01
2019-12
This is Sarah's months.
2020-02
2020-01
2019-12
This is John's months.
2020-02
2020-01
2019-12
{% for key, values in context_data.items %}
<p class="big">This is {{ key }}'s months.</p>
{% for foo2 in values %}
<p class="small">{{ foo2.month }}</p>
{% endfor %}
<br>
{% endfor %}