You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Jinja2按字段分组遍历数据?遇不可哈希类型错误求解

问题描述

数据库结构

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

尝试的Jinja2代码

{% 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 %}

报错信息

unhashable type: 'collections.OrderedDict'

核心问题

仅使用Jinja2(不借助Python预处理数据)能否提取单列并按其分组遍历?


解决方案

可以仅用Jinja2实现分组遍历,你之前的报错原因是selectattr('country')返回的是整个字典对象,而非country字段的具体值,unique过滤器无法对字典去重(字典属于不可哈希类型)。

正确实现代码如下:

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

关键修改点

  • 用map(attribute='country')替换selectattr('country'):map会提取每个字典中country字段的具体值,而selectattr只是筛选出包含country字段的完整字典对象。
  • 修正变量渲染语法:将{country}和{item.name}改为Jinja2标准的{{ country }}和{{ item.name }},否则变量无法被正确解析渲染。

通过以上修改,即可按国家分组,依次展示对应国家的用户名称。

内容的提问来源于stack exchange,提问作者murlex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 21:35:17