此: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