SqlAlchemy: get object instance state
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!
[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)
Better use Inspection API:
from sqlalchemy import inspect
state = inspect(obj)
# Booleans
state.transient
state.pending
state.detached
state.persistent
Another option is object_state, retuning an InstanceState:
from sqlalchemy.orm.util import object_state
state = object_state(obj)
# here are the four states:
state.transient # !session & !identity_key
state.pending # session & !identity_key
state.persistent # session & identity_key
state.detached # !session & identity_key
# and low-level attrs
state.identity_key
state.has_identity # bool(identity_key)
state.session
another option, which lists ALL objects in particular states within a session: http://docs.sqlalchemy.org/en/latest/orm/session.html#session-attributes
# pending objects recently added to the Session
session.new
# persistent objects which currently have changes detected
# (this collection is now created on the fly each time the property is called)
session.dirty
# persistent objects that have been marked as deleted via session.delete(obj)
session.deleted
# dictionary of all persistent objects, keyed on their
# identity key
session.identity_map
精彩评论