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

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

## 根因

在会话关闭或对象被分离后，尝试访问延迟加载的关系属性。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   Eagerly load relationships before closing the session: user = session.query(User).options(joinedload(User.posts)).first()
   ```
2. **** (80% 成功率)
   ```
   Use session.expire_on_commit=False to keep objects usable after commit.
   ```

## 无效尝试

- **** — Adding a detached object may create duplicate or raise errors; it doesn't restore the original session context. (70% 失败率)
- **** — Merge works but may overwrite changes; also it's not ideal for read-only lazy loads. (40% 失败率)
