Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get changed values before committing SQLAlchemy model

I have a SQLAlchemy model instance with new values pending a commit() to write them to the database. How can I check the old values that are in the database without issuing a rollback()?

like image 909
Rafael Avatar asked Sep 29 '26 09:09

Rafael


1 Answers

You can get the history of every SQLAlchemy mapped attribute using the inspection api. See the docs on History for what information is available.

import sqlalchemy as sa

old = {}

for attr in sa.inspect(item).attrs:
    if attr.history.has_changes():
        old[attr.key] = attr.history.deleted
like image 79
davidism Avatar answered Oct 01 '26 00:10

davidism



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!