Home > Blockchain >  Django - compare values of keys in dictionaries in two different lists
Django - compare values of keys in dictionaries in two different lists

Time:08-24

I have two lists of dictionaries that I have pulled from an XML file using elementtree. Each list of dictionaries contains dozens of keys/values but for simplicity sake let's say it's similar to the below:

list1 = [{'id': '100', 'first_name': 'john'}, {'id': '101', 'first_name': 'joe'}]
list2 = [{'id': '100', 'last_name': 'doe'}, {'id': '101', 'last_name': 'bloggs'}]

I'm using Django to build a table with the data and want to put the first names (from list1) and last names (from list2) on the same row of the table where there's a match in the 'id' values, but I can't figure out how to do this.

If I wanted to list them in python I would use:

for v in list1:
    print(v['id'])
    print(v['first_name'])
    for i in list2:
        if i['id'] == v['id']:
            print(i['last_name'])

But I can't figure out how to write this with django tags in the HTML template. Here's what I've tried (and variations thereof):

{% for v in list1 %}
    <tr>
        <td>{{v.id}}</td>
        <td>{{v.first_name}}</td>
        {% for i in list2 %}
            {% if {{v.id}} == {{i.id}} %}
                <td>{{i.last_name}}</td>
            {% endif %}
        {% endfor %}
    </tr>
{% endfor %}

CodePudding user response:

You're using {{}} within {%%}

Django's template engine really doesn't like that.

Write it like this:

        {% for i in list2 %}
            {% if v.id == i.id %}
                <td>{{i.last_name}}</td>
            {% endif %}
        {% endfor %}

Sidenote:

You are comparing ID's. Is it a related object? Is it the same model?

  • Related