跟踪 SQLAlchemy 中的模型更改 [英] Tracking model changes in SQLAlchemy

查看:36
本文介绍了跟踪 SQLAlchemy 中的模型更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想记录每个 SQLAlchemy 模型将执行的操作.

I want to log every action what will be done with some SQLAlchemy-Models.

所以,我有一个 after_insert、after_delete 和 before_update 钩子,我将在其中保存模型的先前和当前表示,

So, I have a after_insert, after_delete and before_update hooks, where I will save previous and current representation of model,

def keep_logs(cls):
    @event.listens_for(cls, 'after_delete')
    def after_delete_trigger(mapper, connection, target):
        pass

    @event.listens_for(cls, 'after_insert')
    def after_insert_trigger(mapper, connection, target):
        pass

    @event.listens_for(cls, 'before_update')
    def before_update_trigger(mapper, connection, target):
        prev = cls.query.filter_by(id=target.id).one()
        # comparing previous and current model


MODELS_TO_LOGGING = (
    User,
)
for cls in MODELS_TO_LOGGING:
    keep_logs(cls)

但是有一个问题:当我试图在 before_update 钩子中查找模型时,SQLA 返回修改后的(脏)版本.如何在更新之前获取模型的先前版本?有没有其他方法可以保持模型更改?

But there is one problem: when I'm trying to find model in before_update hook, SQLA returns modified (dirty) version. How can I get previous version of model before updating it? Is there a different way to keep model changes?

谢谢!

推荐答案

SQLAlchemy 跟踪每个属性的更改.您不需要(也不应该)在事件中再次查询实例.此外,任何已修改的实例都会触发该事件,即使该修改不会更改任何数据.循环遍历每一列,检查它是否已被修改,并存储任何新值.

SQLAlchemy tracks the changes to each attribute. You don't need to (and shouldn't) query the instance again in the event. Additionally, the event is triggered for any instance that has been modified, even if that modification will not change any data. Loop over each column, checking if it has been modified, and store any new values.

@event.listens_for(cls, 'before_update')
def before_update(mapper, connection, target):
    state = db.inspect(target)
    changes = {}

    for attr in state.attrs:
        hist = attr.load_history()

        if not hist.has_changes():
            continue

        # hist.deleted holds old value
        # hist.added holds new value
        changes[attr.key] = hist.added

    # now changes map keys to new values

这篇关于跟踪 SQLAlchemy 中的模型更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆