# 实例 <User at 0x...> 是分离的；merge() 无法进行，因为会话已有一个具有相同主键的不同实例

- **ID:** `python/sqlalchemy-orm-exc-detached-instance-merge-conflict`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

尝试合并一个分离的实例，但会话已跟踪另一个具有相同主键的实例，导致身份冲突。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **Expunge existing instance first** (85% 成功率)
   ```
   Expunge the existing instance from session before merge: session.expunge(existing_instance); session.merge(detached_instance)
   ```
2. **Merge with clean session** (90% 成功率)
   ```
   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% 失败率)
