SQLAlchemy, get object not bound to a Session

If you want a bunch of objects produced by querying a session to be usable outside the scope of the session, you need to expunge them for the session.

In your first function example, you will need to add a line:

session.expunge_all()

before

session.close()

More generally, let’s say the session is not closed right away, like in the first example. Perhaps this is a session that is kept active during entire duration of a web request or something like that. In such cases, you don’t want to do expunge_all. You will want to be more surgical:

for item in lst:
    session.expunge(item)

Leave a Comment