此:Intro to object states列出的四种置换的存在,在-DB /在场的会期:SQLAlchemy的:获取对象实例的状态
transient, pending, persistent & detached
是否有查询给定对象的任何方式返回其中对象在四个状态?
我试过在_sa_instance_state
附近生根,但找不到任何相关的东西。
谢谢!
此:Intro to object states列出的四种置换的存在,在-DB /在场的会期:SQLAlchemy的:获取对象实例的状态
transient, pending, persistent & detached
是否有查询给定对象的任何方式返回其中对象在四个状态?
我试过在_sa_instance_state
附近生根,但找不到任何相关的东西。
谢谢!
更好地利用Inspection API:
from sqlalchemy import inspect
state = inspect(obj)
# Booleans
state.transient
state.pending
state.detached
state.persistent
[更新:这个答案是0.8之前的版本]
发现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)
另一种选择,其中列出了一个会话内特定国家所有对象: 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
请注意,'session.deleted'仅包含delete()和flush()之间的对象,而'inspect(object).deleted'仅在'flush()'后返回True,所以这些不等价。 – qris 2015-04-01 10:27:52
另一种选择是object_state,重新调整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
看起来像是在SQLA中添加了这些属性0.8 – EoghanM 2014-05-15 11:16:07
请注意'state.deleted'只会在'Session.flush()'从数据库中删除记录后才会更新。在'flush()'之前,似乎检查对象上是否调用了Session.delete()'的唯一方法是[在Session.deleted中查找它](http://stackoverflow.com/a/20963631/648162)如@ Erik49所示。 – qris 2015-04-01 10:26:49
做这个'def state(object):return inspect(object)'做同样的事吗? – roy 2016-10-11 08:20:10