简体   繁体   English

在提交SQLAlchemy模型之前获取更改的值

[英]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. 我有一个SQLAlchemy模型实例,其新值等待commit()将它们写入数据库。 How can I check the old values that are in the database without issuing a rollback() ? 如何在不发出rollback()情况下检查数据库中的旧值?

You can get the history of every SQLAlchemy mapped attribute using the inspection api. 您可以使用检查api获取每个SQLAlchemy映射属性的历史记录。 See the docs on History for what information is available. 有关可用信息,请参阅History文档

import sqlalchemy as sa

old = {}

for attr in sa.inspect(item).attrs:
    if attr.history.has_changes():
        old[attr.key] = attr.history.deleted

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM