# sqlalchemy.exc.InvalidRequestError: 一个或多个映射器初始化失败 - 无法继续初始化其他映射器。原始异常: ImportError: 无法从部分初始化的模块 'models' 中导入名称 'Parent'

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

## 根因

定义关系时模块之间的循环导入，导致映射器初始化失败。

## 版本兼容性

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

## 解决方案

1. **Use string references in relationships** (98% 成功率)
   ```
   class Parent(Base):
    __tablename__ = 'parents'
    children = relationship('Child', back_populates='parent')
class Child(Base):
    __tablename__ = 'children'
    parent_id = Column(Integer, ForeignKey('parents.id'))
    parent = relationship('Parent', back_populates='children')
   ```
2. **Use lazy imports inside the relationship definition** (90% 成功率)
   ```
   children = relationship(lambda: Child, back_populates='parent')
   ```

## 无效尝试

- **Moving all models into one file** — This may resolve the import issue but leads to a monolithic, hard-to-maintain codebase. (50% 失败率)
- **Removing the relationship** — The ORM functionality is lost. (90% 失败率)
