I have a database that looks like this:
JavaScript
x
8
1
Name | Phone_no | Country | Zipcode
2
-----------------------------------
3
Foo | 12345 | USA | 92121
4
Bar | 65745 | UK | 15409
5
Arm | 77745 | UAE | 88844
6
Mac | 88845 | USA | 66623
7
Dox | 99945 | UAE | 52624
8
and I want to group the rows on country and display with something like this:
JavaScript
1
7
1
{% for country in addr_db|selectattr('country')|unique|list %}
2
<h1> {country} </h1>
3
{% for item in addr_db | selectattr('country', 'equalto', country) %}
4
<p>{item.name}<p><br>
5
{% endfor %}
6
{% endfor %}
7
The above doesn’t seem to work as the first for loop results in the following error:
JavaScript
1
2
1
unhashable type: 'collections.OrderedDict'
2
Is it possible to extract just one column, and use that to group the rows, just by using jinja2 (i.e. no additional massaging of the database using python) ?
Advertisement
Answer
The error you are seeing is caused by selectattr
as it filters and returns a list of dictionaries, and dictionaries are not hashable types. In order to fix this, you can use the map
filter to extract the country field from each dictionary and return a list of strings instead:
JavaScript
1
7
1
{% for country in addr_db|selectattr('country')|map(attribute='country')|unique|list %}
2
<h1> {{ country }} </h1>
3
{% for item in addr_db | selectattr('country', 'equalto', country) %}
4
<p>{{ item.name }}<p><br>
5
{% endfor %}
6
{% endfor %}
7