Tracking model changes in SQLAlchemy

后端 未结 3 815
半阙折子戏
半阙折子戏 2021-01-31 18:43

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

So, I have a after_insert, after_delete and before_update hooks, where I will save previous and

3条回答
  •  时光取名叫无心
    2021-01-31 19:19

    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
    

提交回复
热议问题