I am trying to create audits (get columns with values before and after Update) Update statement per ORM 2.0 style :
engine = create_engine("sqlite:///sales.db", echo=True)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
class User12(Base):
__tablename__ = "user12"
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
Base.metadata.create_all(engine)
session.execute(insert(User12), [{ "name": "old_name" , "email": "[email protected]"}])
session.commit()
session.close()
After this, if I follow Tracking model changes in SQLAlchemy to track updates, it works, provided I update a certain way. Example :
user = session.execute(select(User12).filter_by(name="old_name")).scalar_one()
Issue is, this way of updating data can be tracked :
user.email = '[email protected]'
But not the ORM 2.0 style update : https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html#orm-queryguide-update-delete-where
stmt = (
update(User12)
.where(User12.name == "old_name")
.values(email='[email protected]')
)
session.execute(stmt)
session.commit()
Can any one please share a working example ? FYI, I am trying to capture audits in a dictionary form -
{col1: [old value, new value]}
I have tried get_history method as mentioned at Tracking model changes in SQLAlchemy but it only works with a specific kind of way of updating not with orm 2.0 style.
synchronize_session
to a value that updates the session.