DetachedInstanceError when accessing relationship after session close in SQLAlchemy
0 reputation · 21 Feb 2025, 23:17 UTC
Goal
Determine the safest lazy‑loading configuration for ORM relationships that are serialized to JSON in a stateless web API while keeping response size predictable and avoiding DetachedInstanceError.
Constraints
- The API creates a short‑lived Session per request and closes it before serialization.
- Relationships may be accessed multiple times during serialization (e.g., nested fields).
- The application must run unchanged on SQLAlchemy 1.4 and 2.x.
- Pagination uses Query.limit().offset() on lazy='dynamic' collections.
Given these conditions, what trade‑offs should guide the choice between lazy='select' and lazy='joined'? How does each strategy interact with request‑scoped session lifecycle and dynamic pagination? Are there established patterns that automatically reattach or expunge objects to prevent the error without manual intervention?