代码之家  ›  专栏  ›  技术社区  ›  EoghanM

SQLAlchemy:获取对象实例状态

  •  27
  • EoghanM  · 技术社区  · 15 年前

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

    transient, pending, persistent & detached
    

    是否有任何方法可以查询给定的对象以返回该对象所处的四种状态中的哪一种?

    我试着在附近扎根 _sa_instance_state 但找不到任何相关的信息。

    谢谢!

    4 回复  |  直到 11 年前
        1
  •  12
  •   kolypto    11 年前

    更好地利用 Inspection API :

    from sqlalchemy import inspect
    state = inspect(obj)
    
    # Booleans
    state.transient
    state.pending
    state.detached
    state.persistent
    
        2
  •  31
  •   EoghanM    11 年前

    [更新:此答案适用于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) 
    
        3
  •  5
  •   Tobu    11 年前

    另一个选择是 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
    
        4
  •  2
  •   egafni    12 年前

    另一个选项,列出会话中特定状态下的所有对象: 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