SqlAlchemy:获取对象实例状态

时间:2010-10-07 20:26:33

标签: sqlalchemy

这:Intro to object states列出了存在于数据库中/存在于会话中的四种排列:

transient, pending, persistent & detached

有没有办法查询给定对象以返回该对象所处的四种状态中的哪一种?

我尝试在_sa_instance_state生根,但找不到任何相关内容。

谢谢!

4 个答案:

答案 0 :(得分:31)

[更新:此答案适用于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) 

答案 1 :(得分:12)

更好地使用Inspection API

from sqlalchemy import inspect
state = inspect(obj)

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

答案 2 :(得分:5)

另一个选项是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

答案 3 :(得分: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