首页 > 解决方案 > 如何在 sqlalchemy 事件“after_update”中获取修改列或更新语句

问题描述

请问,我使用SQLAlchemy事件监听after_update,但是需要获取update语句,或者本次更新了哪些字段,请问有什么方法可以获取?

我查看了官方文档,但没有找到任何获取更新列或更新语句的说明。我搜索时没有找到相关信息。

期待帮助

标签: python-2.6

解决方案


这是我在项目中所做的,它奏效了:

import json

from sqlalchemy import event, inspect


def update_instance_log(mapper, connection, target):
    "listen for the 'after_update' event"

    # this will return a dict with keys of mutated columns and values before update
    old_values = inspect(target).committed_state
    
    # from the old_values above, get the same dict but with updated values
    new_values = {key: inspect(target).dict[key] for key in old_values.keys()}

    table = models.MyLogClass.__table__
    connection.execute(table.insert().values(
      OldValue=json.dumps(old_values),
      NewValue=json.dumps(new_values),
      # ... other values
    ))


event.listen(MyClass, 'after_update', update_instance_log)

推荐阅读