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

Flask+Jinja循环中无法从字典获取部门与角色名称的求助

问题原因与解决方案

核心问题:类型不匹配

你的dept_name和role_name无法显示,根源是字典键的类型与员工数据中的ID类型不匹配:

  • 数据库中用户的role_id、dept_id是字符串类型(比如用户数据里的"2"、"8")
  • 但Python代码里:
    • roles字典的键是整数(2: "Manager")
    • depts字典的键是dept.id,若Department模型的id是整数类型,键也会是整数,和用户的字符串dept_id无法匹配

解决方法(二选一即可)

方法1:修改Python代码,对齐字典键与ID类型

把roles的键改为字符串,同时构建depts时将部门ID转为字符串:

def display_employees():
    employees = Users.query.all()
    departments = Department.query.all()
    depts = {}
    # 把roles的键改为字符串,匹配数据库的role_id类型
    roles = {"2": "Manager", "3": "Employee"}
    for dept in departments:
        # 将部门ID转为字符串,匹配用户的dept_id类型
        depts[str(dept.id)] = dept.name

    return render_template(
        "display_employees.html", employees=employees, depts=depts, roles=roles
    )

方法2:在Jinja模板中转换ID类型

保持Python代码不变,在模板里用int过滤器把员工的dept_id和role_id转为整数,匹配字典键类型:

<table>
    <tr>
        <th>Employee Name</th>
        <th>Department Name</th>
        <th>Employee Role</th>
    </tr>

    {% for emp in employees %}
    <!-- 使用int过滤器转换ID类型 -->
    {% set dept_name = depts[emp.dept_id|int] %}
    {% set role_name = roles[emp.role_id|int] %}
    <tr>
        <td>{{ emp.name }}</td>
        <td>{{ dept_name }}</td>
        <td>{{ role_name }}</td>
    </tr>
    {% endfor %}
</table>

额外建议

检查Users和Department模型的字段类型:如果dept_id、role_id设计为整数类型,建议调整数据库字段类型为整数,从根源避免后续类型匹配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:37:40