Detached instance error SQLAlchemy FastAPI

DetachedInstanceError

Quick Answer

Accessing a lazy-loaded attribute after the session was closed.

Why This Happens

In FastAPI, accessing a lazy-loaded attribute after the session was closed. This is one of the most common FastAPI errors developers encounter. Understanding the root cause helps you fix it quickly and prevent it from recurring.

The Problem

user = db.query(User).first()
db.close()
print(user.posts)  # Detached!

The Fix

user = db.query(User).options(
    joinedload(User.posts)
).first()

Step-by-Step Fix

  1. 1

    Identify the error

    Look at the error message: DetachedInstanceError. This tells you exactly what went wrong.

  2. 2

    Find the cause

    Check the stack trace to find which line of your FastAPI code triggered this error.

  3. 3

    Apply the fix

    Use the corrected code pattern shown above. Test to confirm the error is resolved.

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