# AttributeError：'User' 对象没有属性 'addresses'

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

## 根因

关系未定义或由于在会话外延迟加载而未加载。

## 版本兼容性

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

## 解决方案

1. **Define relationship in model class.** (95% 成功率)
   ```
   class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    addresses = relationship('Address', back_populates='user')
   ```
2. **Eagerly load relationship in query.** (90% 成功率)
   ```
   user = session.query(User).options(joinedload(User.addresses)).first()
print(user.addresses)  # Now available
   ```

## 无效尝试

- **Adding the attribute manually to the class.** — Relationship must be defined via SQLAlchemy ORM; manual attribute breaks mapping. (90% 失败率)
- **Using getattr with default but still accessing lazy attribute.** — Underlying relationship still not loaded; returns None incorrectly. (70% 失败率)
