Syntax_Error
Syntax_Error

Reputation: 6230

Django template get element in list of dictionary by index

I have the following:

item0 = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}, {'itemCode': 'AP01', 'price': 1.2}]
item1 = [{'itemCode': 'BZ001', 'price': 12.55}, {'itemCode': 'BB01', 'price': 34.1}]

In django template I would like to display the price of the elements of each list by index: 15.52, 12.55 then 31.2, 34.1 then 1.2

List sizes might not be equal, so I am sending the size of the largest list.

Iterating over the max list size:

{{i.item|index:forloop.counter0}} gets me {'itemCode': 'AZ001', 'price': 15.52}

If I want price, what can I do?

Doing {{i.item|index:forloop.counter0.price}} is giving me invalid key price at index 0.

In other words, I am sending elements in column order and would like to display them in row order without doing list comprehension using zip on the server.

Any solution?

Upvotes: 1

Views: 3242

Answers (2)

mh-samiei
mh-samiei

Reputation: 111

<ul>
     {% for key, value in dictionary.items %}
     <li><a href="{{key}}">{{value}}</a></li>
     {% endfor %}
</ul>

try using this, reference

Upvotes: 0

Yannic Hamann
Yannic Hamann

Reputation: 5235

Not sure if I get your question right, but this is the code what you are asking for.

views.py:

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['item'] = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}]
        return context

template.html:

{{ item.0.price }}

Results in 15.52


If you want to loop over it you can do it like so:

{% for i in item %}
    {{ i.price }}
{% endfor %}

After you have updated the question, I would do the following:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    item0 = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}, {'itemCode': 'AP01', 'price': 1.2}]
    item1 = [{'itemCode': 'BZ001', 'price': 12.55}, {'itemCode': 'BB01', 'price': 34.1}]
    import itertools
    context['zip_longest'] = itertools.zip_longest(item0, item1)
    return context

template.html:

{% for element in zip_longest %}
    {% for item in element %}
        {% if item %}
            {{ item.price }} <br>
        {% endif %}
    {% endfor %}
{% endfor %}

Results in:

15.52 
12.55 
31.2 
34.1 
1.2 

In my opinion, it's nothing wrong with using zip_longest, since it yields the values from a generator.

Upvotes: 2

Related Questions