python runtime_error ai_generated true

sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <User at 0x...> is not bound to a Session; lazy load operation of attribute 'addresses' cannot proceed

ID: python/sqlalchemy-lazy-load-error

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Attempting to access a lazy-loaded relationship on a detached instance, which requires an active session.

generic

中文

尝试访问已分离实例上的延迟加载关系,这需要活动会话。

Workarounds

  1. 95% success Eagerly load the relationship before detaching
    user = session.query(User).options(joinedload(User.addresses)).first()
    session.close()
    print(user.addresses)  # Works because addresses are already loaded
  2. 90% success Use session.merge() to reattach the instance
    user = session.merge(detached_user)
    print(user.addresses)

Dead Ends

Common approaches that don't work:

  1. Re-opening the session and reusing the same instance 75% fail

    The instance is still detached; you need to merge or reattach it.

  2. Calling session.close() before accessing the attribute 85% fail

    Closing the session makes the instance detached.