Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy: get object instance state

Tags:

sqlalchemy

This: Intro to object states lists the four permutations of presence-in-DB/presence-in-session:

transient, pending, persistent & detached 

Is there any way of querying a given object to return which of the four states the object is in?

I tried rooting around in _sa_instance_state but couldn't find anything relevant.

Thanks!

like image 846
EoghanM Avatar asked Oct 07 '10 20:10

EoghanM


People also ask

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.

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.

What object does SQLAlchemy query return?

It returns an instance based on the given primary key identifier providing direct access to the identity map of the owning Session. It creates a SQL JOIN against this Query object's criterion and apply generatively, returning the newly resulting Query.

What is Sessionmaker in SQLAlchemy?

Python Flask and SQLAlchemy ORM In order to interact with the database, we need to obtain its handle. A session object is the handle to database. Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine object created earlier. from sqlalchemy.


1 Answers

[Update: This answer is for versions before 0.8]

Found it here:

from sqlalchemy.orm import object_session  from sqlalchemy.orm.util import has_identity   # transient:  object_session(obj) is None and not has_identity(obj)  # pending:  object_session(obj) is not None and not has_identity(obj)  # detached:  object_session(obj) is None and has_identity(obj)  # persistent:  object_session(obj) is not None and has_identity(obj)  
like image 92
EoghanM Avatar answered Sep 25 '22 06:09

EoghanM