【问题标题】:How to get the modify column or update statement in sqlalchemy event "after_update"如何在 sqlalchemy 事件“after_update”中获取修改列或更新语句
【发布时间】:2019-12-10 15:59:48
【问题描述】:

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

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

期待帮助

【问题讨论】:

    标签: python-2.6


    【解决方案1】:

    这是我在项目中所做的,并且成功了:

    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)
    

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 1970-01-01
      • 2014-06-02
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多