python
runtime_error
ai_generated
true
sqlalchemy.orm.exc.DetachedInstanceError: Instance <User at 0x...> is not bound to a Session; attribute refresh operation cannot proceed
ID: python/flask-sqlalchemy-detachedinstanceerror
80%Fix Rate
87%Confidence
0Evidence
2024-06-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
| 3.x | active | — | — | — |
Root Cause
Accessing an attribute of an ORM object after the session that loaded it has been closed or committed.
generic中文
在加载 ORM 对象的会话关闭或提交后访问该对象的属性。
Workarounds
-
90% success
user = session.query(User).options(joinedload(User.posts)).first() # use user.posts before session.close()
-
85% success
Use `db.session` within the request context; avoid manual session.close().
Dead Ends
Common approaches that don't work:
-
60% fail
This only prevents expiration on commit, not detachment after session close.
-
80% fail
The session is already closed, so refresh fails.