In sqlalchemy, how to check if a model is attached on session?

To answer the first question if an object is attached to a session, you can use:

print(obj in DBSession)

Or use inspect:

from sqlalchemy import inspect
print(not inspect(obj).detached)

See also: http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html#getting-the-current-state-of-an-object


Session is not attached with any model, but rather it is attached to the object of the model. You will get the attached session from the object with the help of object_session method.