python - 数据库更新后,如何获取 SQLAlchemy ORM 对象的先前状态?

标签 python orm sqlalchemy crud

问题是我不知道如何使用 SQLAlchemy 在对象进入新状态时通知我。

我正在使用 SQLAlchemy ORM(声明式)更新对象:

class Customer(declarative_base()):

    __table_name__ = "customer"

    id = Column(Integer, primary_key=True)
    status = Column(String)

我想知道对象何时进入状态。特别是在发布更新之后以及状态发生变化时。例如。 Customer.status == 'registered' 之前状态不同。

我目前正在使用 'set' 属性事件执行此操作:

from sqlalchemy import event
from model import Customer

def on_set_attribute(target, value, oldvalue, initiator):
    print target.status
    print value
    print oldvalue

event.listen(
        Customer.status,
        'set',
        on_set_attribute,
        propagate=True,
        active_history=True)

每次对该属性调用“set”时,我的代码都会触发,并且我会检查 valueoldvalue 是否不同。问题在于 target 参数未完全形成,因此尚未填充所有属性值。

有更好的方法吗?谢谢!

最佳答案

我的解决方案是使用“after_flush”SessionEvent 而不是“set”AttributeEvent。

非常感谢agronholm谁提供了专门检查对象值和旧值的示例 SessionEvent 代码。

下面的解决方案是修改他的代码:

def get_old_value(attribute_state):
    history = attribute_state.history
    return history.deleted[0] if history.deleted else None


def trigger_attribute_change_events(object_):
    for mapper_property in object_mapper(object_).iterate_properties:
        if isinstance(mapper_property, ColumnProperty):
            key = mapper_property.key
            attribute_state = inspect(object_).attrs.get(key)
            history = attribute_state.history

            if history.has_changes():
                value = attribute_state.value
                # old_value is None for new objects and old value for dirty objects
                old_value = get_old_value(attribute_state)
                handler = registry.get(mapper_property)
                if handler:
                    handler(object_, value, old_value)


def on_after_flush(session, flush_context):
    changed_objects = session.new.union(session.dirty)
    for o in changed_objects:
        trigger_attribute_change_events(o)

event.listen(session, "after_flush", on_after_flush)

registry 是一个字典,其键是 MapperProperty 的,其值是事件处理程序。 sessioneventinspectobject_mapper 都是 sqlalchemy 类和函数。

关于python - 数据库更新后,如何获取 SQLAlchemy ORM 对象的先前状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15642286/

相关文章:

java - 与父实体一起驱逐依赖集合

php - 如何使用关系在laravel数据库中插入嵌套的二维数组

python - 在 Python Pandas 中将 NaN 转换为 Oracle Null

python - sqlalchemy - 连接表的限制就好像它们没有连接一样

python - 如何在 CGIAr 中使用 Python 重定向到另一个页面

python - 无法在 Windows 10 上使用 pip 安装 Vowpalwabbit

java - org.hibernate.NonUniqueObjectException。如何修复它?

python - 如何将此 SQL 转换为 Django 查询?

python - 使用 python graphviz ImportError : No module named _gv

python - SQLAlchemy + MySQL - 在原始查询中将表名作为参数传递