# sqlalchemy.orm.exc.DetachedInstanceError: 父实例 <User at 0x...> 未绑定到会话；属性 'addresses' 的延迟加载操作无法进行

- **ID:** `python/sqlalchemy-lazy-load-error`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

尝试访问已分离实例上的延迟加载关系，这需要活动会话。

## 版本兼容性

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

## 解决方案

1. **Eagerly load the relationship before detaching** (95% 成功率)
   ```
   user = session.query(User).options(joinedload(User.addresses)).first()
session.close()
print(user.addresses)  # Works because addresses are already loaded
   ```
2. **Use session.merge() to reattach the instance** (90% 成功率)
   ```
   user = session.merge(detached_user)
print(user.addresses)
   ```

## 无效尝试

- **Re-opening the session and reusing the same instance** — The instance is still detached; you need to merge or reattach it. (75% 失败率)
- **Calling session.close() before accessing the attribute** — Closing the session makes the instance detached. (85% 失败率)
