# sqlalchemy.exc.InvalidRequestError: 初始化映射器 Mapper[User] 时，表达式 'Post' 无法定位名称 ('Post')。如果这是一个类名，请考虑在两个依赖类都定义后，将此 relationship() 添加到类中。

- **ID:** `python/sqlalchemy-circular-import-models`
- **领域:** python
- **类别:** module_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

模型模块之间的循环导入导致在配置映射器时，某个模型类尚未定义。

## 版本兼容性

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

## 解决方案

1. **** (90% 成功率)
   ```
   Use string-based relationship references: class User(Base): posts = relationship('Post', back_populates='user') - and ensure Post is defined later in the same module or imported lazily.
   ```
2. **** (85% 成功率)
   ```
   Use the 'late-binding' pattern: define relationships in a separate configure_mappers() call after all models are imported: from sqlalchemy.orm import configure_mappers; configure_mappers()
   ```

## 无效尝试

- **** — Top-level imports still trigger the same circular dependency; the classes are not yet defined at import time. (90% 失败率)
- **** — If the __init__.py imports both modules, it still hits the circular reference during module initialization. (80% 失败率)
