python-2.6 - 如何在 sqlalchemy 事件“after_update”中获取修改列或更新语句
问题描述
请问,我使用SQLAlchemy事件监听after_update,但是需要获取update语句,或者本次更新了哪些字段,请问有什么方法可以获取?
我查看了官方文档,但没有找到任何获取更新列或更新语句的说明。我搜索时没有找到相关信息。
期待帮助
解决方案
这是我在项目中所做的,它奏效了:
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)
推荐阅读
- ios - 你如何使用 ASWebAuthenticationSession、本机应用程序、https:需要重定向?
- windows - 如何(使用 New-GPLink)将 GPO 链接到封装在另一个组织单位中的组织单位
- apache-spark - 在 PySpark 中并行化 SparkSession
- sql - SQL 2018 工作室中的是/否列
- javascript - 需要帮助解决如何为 html/css 滑块添加更好的图像标题
- python - 您可以为字典中的项目分配多个值吗?
- sql - 我正在将以下 oracle 查询转换为 bigquery,但结果记录数不同
- java - 如何从 Java 中的 ByteBuffer 读取和存储 64 位 UNSIGNED long?存放在哪里,因为长时间无法容纳它?
- python - 将混合类型 DF 列中的浮点数转换为字符串使用科学记数法
- algorithm - 从comp类算法时间问题,n = 100 = 10秒,O(n ^ 2)n = 500的时间是多少