2010-10-07 23 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

相關問題