Tracking model changes in SQLAlchemy

后端 未结 3 850
半阙折子戏
半阙折子戏 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:13

    If an attribute is expired (which sessions do by default on commit) the old value is not available unless it was loaded before being changed. You can see this with the inspection.

    state = inspect(entity)
    session.commit()
    state.attrs.my_attribute.history  # History(added=None, unchanged=None, deleted=None)
    # Load history manually
    state.attrs.my_attribute.load_history()
    state.attrs.my_attribute.history  # History(added=(), unchanged=['my_value'], deleted=())
    

    In order for attributes to stay loaded you can not expire entities by settings expire_on_commit to False on the session.

提交回复
热议问题