python
runtime_error
ai_generated
true
实例 <User at 0x...> 是分离的;merge() 无法进行,因为会话已有一个具有相同主键的不同实例
sqlalchemy.orm.exc.DetachedInstanceError: Instance <User at 0x...> is detached; merge() cannot proceed because the session already has a different instance with the same primary key
ID: python/sqlalchemy-orm-exc-detached-instance-merge-conflict
80%修复率
82%置信度
0证据数
2025-09-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
尝试合并一个分离的实例,但会话已跟踪另一个具有相同主键的实例,导致身份冲突。
English
Attempting to merge a detached instance when the session already tracks another instance with the same primary key, causing identity conflict.
解决方案
-
85% 成功率 Expunge existing instance first
Expunge the existing instance from session before merge: session.expunge(existing_instance); session.merge(detached_instance)
-
90% 成功率 Merge with clean session
Use session.merge() with a new instance that does not conflict, or ensure the session is clean before merging.
无效尝试
常见但无效的做法:
- Deleting existing instance 60% 失败
- Using add() instead 70% 失败