python orm_error ai_generated true

sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session

ID: python/sqlalchemy-detachedinstanceerror

Also available as: JSON · Markdown
88%Fix Rate
90%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Accessing a lazy-loaded relationship after the session is closed.

generic

Workarounds

  1. 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

  2. 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:

  1. Use expire_on_commit=False globally 60% fail

    May serve stale data across requests

Error Chain

Frequently confused with: