SQLAlchemy – DetachedInstanceError parent instance is not bound to a Session

Solution for SQLAlchemy – DetachedInstanceError parent instance is not bound to a Session
is Given Below:

I saw many posts about this error, however none of the solutions worked for me.

My sessions are created using contextmanager just the same as in the docs: https://docs.sqlalchemy.org/en/13/orm/session_basics.html

I’m querying (simple select and join) objects from MSSQL and it works fine, however when trying to access objects that were retrieved from DB I get the error mentioned.

When I comment the session.commit() and session.close() lines, it seems to work fine.

How can I fix that so I can also commit and close connection?

I tried:

1.Using sessions maker instead of simply session

2.Configuring expire_on_commit=False

3.Calling session.expunge_all() right after the yield, and also right after the query execution

None of these worked. What else could work?