【发布时间】:2019-12-10 15:59:48
【问题描述】:
请问,我使用SQLAlchemy事件监听after_update,但是需要获取update语句,或者这次更新了哪些字段,请问可以获取什么方法?
我查看了官方文档,但没有找到任何获取更新列或更新语句的说明。我搜索的时候没有找到相关信息。
期待帮助
【问题讨论】:
标签: python-2.6
请问,我使用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)
【讨论】: