这:对象状态简介列出了存在于数据库中/存在于会话中的四种排列:
transient, pending, persistent & detached
Run Code Online (Sandbox Code Playgroud)
是否有任何方法可以查询给定对象以返回对象所处的四种状态中的哪一种?
我尝试过根,_sa_instance_state但找不到任何相关的东西.
谢谢!
Eog*_*anM 31
[更新:此答案适用于0.8之前的版本]
在这里找到它:
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)
Run Code Online (Sandbox Code Playgroud)
kol*_*pto 13
更好地使用Inspection API:
from sqlalchemy import inspect
state = inspect(obj)
# Booleans
state.transient
state.pending
state.detached
state.persistent
Run Code Online (Sandbox Code Playgroud)
另一个选项是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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8162 次 |
| 最近记录: |