# sqlalchemy.exc.IntegrityError: (psycopg2.errors.ForeignKeyViolation) 在表 "orders" 上插入或更新违反了外键约束 "orders_user_id_fkey"

- **ID:** `python/sqlalchemy-foreign-key-violation`
- **领域:** python
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

尝试插入一行，其外键值在引用表中不存在。

## 版本兼容性

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

## 解决方案

1. **Ensure the referenced record exists before inserting** (98% 成功率)
   ```
   user = session.query(User).filter_by(id=user_id).first()
if user:
    order = Order(user_id=user.id)
    session.add(order)
    session.commit()
   ```
2. **Use a transaction with rollback on error** (90% 成功率)
   ```
   try:
    session.add(order)
    session.commit()
except IntegrityError:
    session.rollback()
    # Handle the error
   ```

## 无效尝试

- **Disabling foreign key checks temporarily** — This can lead to data inconsistency and is not a permanent fix. (80% 失败率)
- **Ignoring the error and retrying** — The same violation will occur unless the data is corrected. (100% 失败率)
