D
D
Denis Lvov2019-10-16 00:12:59
Django
Denis Lvov, 2019-10-16 00:12:59

How to get one of the dictionaries from a complex dictionary in a loop in django?

Let's say we have an impromptu dictionary:

dict = {'day_1': {
                 'name': 'Иван'; 'card': {
                                          '1': 'кроссовки'; '2': 'кепка'}}, 
           'day_2': {
                 'name': 'Вася'; 'card': {
                                          '1': 'тетрадь'; '2': 'ручка'}}
}

{% for y, dict_1 in dict.items %}
     {% for y, dict_2 in dict_1 ????? %}
           <p>...</p>
     {% endfor %}
{% endfor %}

the question is actually in the second cycle what to do?
how to get data by key 'card'?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Lvov, 2019-10-16
@dwenlvov

Found a solution:
Create your own filter.
In the application folder, create a folder temlatetags
In it __init__.py and for example filters.py
In filters.py:

from django import template

register = template.Library()

@register.filter
def get_item(dictionary, key):
    return dictionary[key]

in html:
{% for y, dict_1 in dict.items %}
     {% load filters %}
     {% with item=dict_1|get_item:'card' %}
          {% for y, dict_2 in item.items %}
               <p>dict_2</p>    #словарь card
          {% endfor %}
     {% endwith %}
{% endfor %}

something like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question