# sqlalchemy.exc.IntegrityError: (psycopg2.errors.ForeignKeyViolation) insert or update on table "orders" violates foreign key constraint "orders_user_id_fkey"

- **ID:** `python/sqlalchemy-foreign-key-violation`
- **Domain:** python
- **Category:** data_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

Attempting to insert a row with a foreign key value that does not exist in the referenced table.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.x | active | — | — |

## Workarounds

1. **Ensure the referenced record exists before inserting** (98% success)
   ```
   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% success)
   ```
   try:
    session.add(order)
    session.commit()
except IntegrityError:
    session.rollback()
    # Handle the error
   ```

## Dead Ends

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