SQLAlchemy DetachedInstanceError

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

Quick Answer

You are accessing a lazy-loaded relationship after the session closed. Use eager loading or access data while the session is open.

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)  # DetachedInstanceError

The 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 user

Step-by-Step Fix

  1. 1

    Use eager loading

    Add joinedload() or subqueryload() to the query.

  2. 2

    Access data in session

    Access lazy-loaded relationships while session is open.

  3. 3

    Keep session scope wider

    Keep session open for the entire operation.

Bugsly 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