SqlAlchemy:获取对象实例状态
这:列出了DB/presence in session中存在的四种排列:SqlAlchemy:获取对象实例状态,sqlalchemy,Sqlalchemy,这:列出了DB/presence in session中存在的四种排列: transient, pending, persistent & detached 有没有办法查询给定对象以返回该对象处于四种状态中的哪一种 我试图在\u sa\u instance\u state中搜索,但找不到任何相关内容 谢谢 [更新:此答案适用于0.8之前的版本] 找到它: 另一个选项列出会话中处于特定状态的所有对象: 另一个选项是,重新调整: 更好地使用: 看起来这些属性是在SQLA0.8中添加的,这
transient, pending, persistent & detached
有没有办法查询给定对象以返回该对象处于四种状态中的哪一种
我试图在\u sa\u instance\u state
中搜索,但找不到任何相关内容
谢谢 [更新:此答案适用于0.8之前的版本] 找到它:
另一个选项列出会话中处于特定状态的所有对象: 另一个选项是,重新调整: 更好地使用:
看起来这些属性是在SQLA0.8中添加的,这绝对不是最明显的方式!如果您使用
inspect(obj)
as,我认为代码更具可读性。谢谢@qris-已经更改了已接受的答案。问题在引入inspect system之前提出。请注意,状态。已删除的仅在会话后更新。flush()
实际上从数据库中删除记录。在flush()
之前,检查对象上是否调用了Session.delete()
的唯一方法似乎是按照@Erik49的建议。此def状态(对象):返回检查(对象)
是否执行相同操作?请注意Session.deleted
仅包含delete()
和flush()之间的对象
,而检查(对象)。已删除的仅在刷新()后返回True,因此它们不是等效的。
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)
# 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
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
from sqlalchemy import inspect
state = inspect(obj)
# Booleans
state.transient
state.pending
state.detached
state.persistent