SQLAlchemy ORM 2.0 - create audits (Insert/ Update/ Delete) MySQL #11375
Replies: 1 comment 3 replies
-
note there are two different ways to do UPDATES with SQLAlchemy ORM.
From there, we can look at the bulk method in question. This form:
is a command that one uses to emit this exact SQL to the database:
That's it! if you log into your database and type that command, it will run the UPDATE. What are the "old" values in the table? Well when you emit an UPDATE, they're gone! SQLAlchemy has no additional powers in this area, it just emits commands and gets results, just as you might do on your database's command line tool. if you want to know what "name" was previously, you would need to SELECT it first before updating the table. If this is PostgreSQL, there may be ways to use CTEs to mix these two operations into a single statement that uses RETURNING, and I would ask on PostgreSQL related boards how to get the old value of a row while UPDATEing it at the same time. short answer though, nothing has changed. Use the same unit of work techniques everyone has used for decades. |
Beta Was this translation helpful? Give feedback.
-
I am trying to create audits (get columns with values before and after Update) Update statement per ORM 2.0 style :
Example :
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()
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
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.
Thanks
Beta Was this translation helpful? Give feedback.
All reactions