gpt4 book ai didi

python - Django//如何在模板中显示复杂的深度数据

转载 作者:行者123 更新时间:2023-12-01 06:22:34 25 4
gpt4 key购买 nike

Django 2.2//

Python 3.6//

<小时/>

我有一个使用“列表”和“字典”组合创建的上下文。

数据结构如下所示。

{ 
"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

但我无法获得更多深度数据。

例如,我想获取 Mike 的所有月份(2020-02、2020-01、2019-12)

第二次尝试..

{% for foo in context_data %}
<p class="big">This is {{ foo }}'s months.</p>
{% for foo2 in foo %}
<p class="small">{{ foo2.months }}</p>
{% endfor %}
{% endfor %}

# but it's showing nothing

第三次尝试..

{% 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

第三个代码循环“Mike”字符串..不是 Mike 的数据。

我希望这样显示。

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

我该怎么办?

最佳答案

您仅迭代键,应该使用 items 到字典迭代值。

{% 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 %}

关于python - Django//如何在模板中显示复杂的深度数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60291746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com