python runtime_error ai_generated true

sqlalchemy.orm.exc.UnmappedInstanceError:类 'builtins.dict' 未映射

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.dict' is not mapped

ID: python/sqlalchemy-orm-session-merge-error

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2025-10-05首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

向 session.merge() 传递字典而不是映射类实例。

English

Passing a dictionary instead of a mapped class instance to session.merge().

generic

解决方案

  1. 95% 成功率 Create mapped instance from dict.
    user_data = {'id': 1, 'name': 'Alice'}
    user = User(**user_data)
    merged_user = session.merge(user)
  2. 90% 成功率 Use session.execute() with insert statement.
    from sqlalchemy import insert
    stmt = insert(User).values(**user_data)
    session.execute(stmt)

无效尝试

常见但无效的做法:

  1. Converting dict to object manually without proper mapping. 80% 失败

    Object still not recognized by ORM.

  2. Using session.add() with dict. 90% 失败

    Same error; session expects mapped instances.