2010-10-07 21 views

回答

10

更好地利用Inspection API

from sqlalchemy import inspect 
state = inspect(obj) 

# Booleans 
state.transient 
state.pending 
state.detached 
state.persistent 
+0

请注意'state.deleted'只会在'Session.flush()'从数据库中删除记录后才会更新。在'flush()'之前,似乎检查对象上是否调用了Session.delete()'的唯一方法是[在Session.deleted中查找它](http://stackoverflow.com/a/20963631/648162)如@ Erik49所示。 – qris 2015-04-01 10:26:49

+0

做这个'def state(object):return inspect(object)'做同样的事吗? – roy 2016-10-11 08:20:10

30

[更新:这个答案是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) 
+0

这绝对不是最明显的方式!如果您使用'inspect(obj)'[如上面的@kolypto](http://stackoverflow.com/a/25427235/648162)所示,我认为代码更具可读性。 – qris 2015-04-01 10:09:55

+0

谢谢@qris--已经改变了接受的答案。在检查系统引入之前,问题出现了。 – EoghanM 2015-04-02 11:39:29

2

另一种选择,其中列出了一个会话内特定国家所有对象: 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 
+0

请注意,'session.deleted'仅包含delete()和flush()之间的对象,而'inspect(object).deleted'仅在'flush()'后返回True,所以这些不等价。 – qris 2015-04-01 10:27:52

3

另一种选择是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 
+0

看起来像是在SQLA中添加了这些属性0.8 – EoghanM 2014-05-15 11:16:07

相关问题