Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In sqlalchemy, how to check if one object of model is attached on session? and how to get attached session of one model object.

like image 585
kerwin Avatar asked Mar 16 '12 03:03

kerwin


People also ask

What is _sa_instance_state in SQLAlchemy?

_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance.

How does SQLAlchemy Session work?

What does the Session do? One of the core concepts in SQLAlchemy is the Session . A Session establishes and maintains all conversations between your program and the databases. It represents an intermediary zone for all the Python model objects you have loaded in it.

What is Session commit SQLAlchemy?

Session. commit() is used to commit the current transaction. It always issues Session. flush() beforehand to flush any remaining state to the database; this is independent of the “autoflush” setting.

What does all () do in SQLAlchemy?

all() method. The Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present.


1 Answers

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

like image 129
tsauerwein Avatar answered Nov 13 '22 05:11

tsauerwein