python runtime_error ai_generated true

sqlalchemy.orm.exc.DetachedInstanceError: Instance <User at 0x...> is not bound to a Session

ID: python/sqlalchemy-detached-instance-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-04-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Attempting to access or modify an ORM instance that has been detached from its session, usually after session.close() or session.expunge_all().

generic

中文

尝试访问或修改一个已与会话分离的ORM实例,通常是在调用 session.close() 或 session.expunge_all() 之后。

Workarounds

  1. 95% success Use session.merge() to reattach the instance
    merged_user = session.merge(detached_user)
    print(merged_user.name)
  2. 85% success Refresh the instance with session.refresh() after reattaching
    session.add(detached_user)
    session.refresh(detached_user)

Dead Ends

Common approaches that don't work:

  1. Calling session.add() on the detached instance 80% fail

    The instance is not in a pending state; it needs to be merged first.

  2. Reopening the session and reusing the same instance 70% fail

    The instance's state is stale; you need to merge or refresh it.