Reputation: 447
Django 2.2//
python 3.6//
I have a context created with a combination of 'list' and 'dictionary'.
The data structure is shown below.
{
"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
}
]
}
I'm trying to display this data through a loop in template.
First I'v tried. It shows nice result.
{% for foo in context_data %}
<p>{{ foo }}</p>
{% endfor %}
# result
Mike
Jaden
Sarah
John
But I can't get more depth data.
For example, I want to get Mike's all months (2020-02, 2020-01, 2019-12)
Second tried..
{% 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
Third tried..
{% 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
Third code looping "Mike" string.. not Mike's under data.
I expect showing like this.
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
How can I this?
Upvotes: 1
Views: 101
Reputation: 615
You are iterating only keys, should iterate values using items to dictionary.
{% 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 %}
Upvotes: 1