# sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session; attribute refresh operation cannot proceed

- **ID:** `python/flask-sqlalchemy-detached-instance-error`
- **Domain:** python
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

Accessing lazy-loaded attributes on a SQLAlchemy object after its session has been closed, common in Flask when sessions are removed at request end.

## Version Compatibility

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

## Workarounds

1. **** (90% success)
   ```
   Use joined loading: query with .options(joinedload(MyModel.relationship)) to eagerly load data.
   ```
2. **** (95% success)
   ```
   Access all needed attributes within the session scope, e.g., in the view function before returning.
   ```

## Dead Ends

- **** — Setting expire_on_commit=False can prevent expiration but still fails if session is closed. (60% fail)
- **** — Re-attaching the object with db.session.add() fails because the instance is already persistent. (80% fail)
