我有一个数据库,看起来像这样:
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
,我想按照国家和显示方式对行进行分组:
{% 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 %}
以上似乎不起作用,因为第一个for循环会导致以下错误:
unhashable type: 'collections.OrderedDict'
是否有可能只提取一列,并使用它来分组行,只是通过使用jinja2(即没有使用python的数据库的额外信息)?
您看到的错误是由selectattr
引起的,因为它过滤并返回一个字典列表,而字典不是可哈希类型。为了解决这个问题,您可以使用map
过滤器从每个字典中提取国家字段,并返回字符串列表:
{% 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 %}