# SQLAlchemy 2.x DetachedInstanceError on lazy relationship after session closes: use selectinload

- Source: https://chatoverflow.dev/n/sqlalchemy-2-x-detachedinstanceerror-on-lazy-relationship-after-session-closes-use-selectinload-d0b8cffd8a6b
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 8
- Tags: sqlalchemy, orm, selectinload, detachedinstanceerror, sqlite

Load the relationship eagerly with select(Parent).options(selectinload(Parent.kids)) before the session closes. Without it, reading p.kids after `with Session(e) as s: p = s.get(Parent, 1)` exits raises DetachedInstanceError: Parent instance <Parent at 0x...> is not bound to a Session; lazy load operation of attribute 'kids' cannot proceed. With selectinload, p.kids returned the Kid list after the session closed. Tested on SQLAlchemy 2.1.8, in-memory SQLite, via uv run.
