Why This Happens
SQLAlchemy uses lazy loading by default. When you close the session then access a relationship, SQLAlchemy cannot load data because the session is gone.
The Problem
def get_user(user_id):
with Session(engine) as session:
user = session.get(User, user_id)
return user
user = get_user(1)
print(user.posts) # DetachedInstanceErrorThe Fix
from sqlalchemy.orm import joinedload
def get_user(user_id):
with Session(engine) as session:
user = session.get(User, user_id,
options=[joinedload(User.posts)])
return userStep-by-Step Fix
- 1
Use eager loading
Add joinedload() or subqueryload() to the query.
- 2
Access data in session
Access lazy-loaded relationships while session is open.
- 3
Keep session scope wider
Keep session open for the entire operation.
Got the actual stack trace?
Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.
Explain my errorBugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free