Python "sqlalchemy.orm.exc.DetachedInstanceError" in CI
DetachedInstanceError is raised when you access an unloaded (lazy) attribute on an ORM object whose Session has been closed or committed-and-expired. The object is detached and can no longer load from the database.
What this error means
A test fails with "sqlalchemy.orm.exc.DetachedInstanceError: Instance <User at 0x...> is not bound to a Session; attribute refresh operation cannot proceed" when reading a relationship outside the session.
pytest
sqlalchemy.orm.exc.DetachedInstanceError: Instance <User at 0x...> is not bound to a Session; attribute refresh operation cannot proceedCommon causes
Accessing a lazy attribute after the session closed
The fixture returned an object, the session ended, then the test touched a relationship that needed a query.
expire_on_commit leaving attributes unloaded
After commit, attributes are expired; accessing them outside an open session triggers a refresh that cannot run.
How to fix it
Keep the session open or eager-load what you need
- Keep the session alive for the scope where the object is used.
- Eager-load relationships you will access (joinedload/selectinload).
- Set expire_on_commit=False on the test session if you read attributes after commit.
Python
Session = sessionmaker(bind=engine, expire_on_commit=False)How to prevent it
- Scope object usage to an open session.
- Eager-load relationships needed outside the session.
- Use expire_on_commit=False where post-commit reads are intended.
Related guides
Python "sqlalchemy.exc.IntegrityError: UNIQUE constraint failed" in CIFix "sqlalchemy.exc.IntegrityError: UNIQUE constraint failed" in tests in CI - a row violated a unique constr…
Python "alembic.util.exc.CommandError: Target database is not up to date" in CIFix "alembic.util.exc.CommandError: Target database is not up to date" in CI - alembic refused to autogenerat…
Python "factory_boy DjangoModelFactory not registered" in CIFix factory_boy errors where a DjangoModelFactory is not wired up in CI - the factory is unregistered with py…