Home > database >  how to iterate over one field in jinja2
how to iterate over one field in jinja2

Time:12-30

I have a database that looks like this:

Name | Phone_no | Country | Zipcode
-----------------------------------
Foo  | 12345    | USA     | 92121
Bar  | 65745    | UK      | 15409
Arm  | 77745    | UAE     | 88844
Mac  | 88845    | USA     | 66623
Dox  | 99945    | UAE     | 52624

and I want to group the rows on country and display with something like this:

{% for country in addr_db|selectattr('country')|unique|list %}
   <h1> {country} </h1>
   {% for item in addr_db | selectattr('country', 'equalto', country) %}
      <p>{item.name}<p><br>
   {% endfor %}
{% endfor %}

The above doesn't seem to work as the first for loop results in the following error:

unhashable type: 'collections.OrderedDict'

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) ?

CodePudding user response:

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:

{% for country in addr_db|selectattr('country')|map(attribute='country')|unique|list %}
   <h1> {{ country }} </h1>
   {% for item in addr_db | selectattr('country', 'equalto', country) %}
      <p>{{ item.name }}<p><br>
   {% endfor %}
{% endfor %}
  • Related