0

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.

5
  • I've never tried it, but it might be worth checking whether the audit is updated if you set synchronize_session to a value that updates the session. Commented May 9 at 15:59
  • @snakecharmerb Sure, will research. Can you please share a link that shows how it is used ? Thanks. Commented May 9 at 16:14
  • @snakecharmerb Found a link. Commented May 9 at 16:17
  • @snakecharmerb Audit gets updated and I can access the new value (which I can get by adding a returning clause to the update object as well, without using synchronize_session). But, I have not been able to access the old value that is getting updated. Commented May 9 at 19:19
  • Asked and answered on GitHub here Commented May 10 at 16:23

0