python
orm_error
ai_generated
true
sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session
ID: python/sqlalchemy-detachedinstanceerror
88%Fix Rate
90%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
Accessing a lazy-loaded relationship after the session is closed.
genericWorkarounds
-
92% success Eagerly load relationships: joinedload/subqueryload in query
from sqlalchemy.orm import joinedload query.options(joinedload(Model.relation))
Sources: https://docs.sqlalchemy.org/en/20/orm/queryguide/relationships.html
-
88% success Access attributes within the session context (before closing)
before closing
Sources: https://docs.sqlalchemy.org/en/20/orm/session_basics.html
Dead Ends
Common approaches that don't work:
-
Use expire_on_commit=False globally
60% fail
May serve stale data across requests
Error Chain
Frequently confused with: