如何获取已更改字段的原始值? [英] How to get the original value of changed fields?

查看:204
本文介绍了如何获取已更改字段的原始值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用sqlalchemy作为我的orm,并使用declarative作为基础.

I'm using sqlalchemy as my orm, and use declarative as Base.

Base = declarative_base()
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)

我的问题是,我如何知道用户已被修改,以及如何在不再次查询数据库的情况下获取原始值?

My question is, how do I know a user has been modified, and how to get the original values without query database again?

user = Session.query(User).filter_by(id=user_id).first()
# some operations on user
....
# how do I know if the user.name has been changed or not?
...
# How do get the original name?

提前谢谢!

更新

我发现方法get_history可以获取字段的历史值,但是我不确定这是否是适合我目的的方法.

I found a method get_history can get the history value of a field, but I'm not sure if it is the correct method for my purpose.

from sqlalchemy.orm.attributes import get_history
user = Session.query(User).first()
print user.name  # 'Jack'
print get_history(user, 'name') # ((),['Jack'],())

user.name = 'Mike'
print get_history(user, 'name') # (['Mike'], (),['Jack'])

因此,我们可以检查get_history的值,但这是最好的方法吗?

So, we can check the value of get_history, but is it the best method?

推荐答案

\\要查看user是否已修改,可以检查user in session.dirty.如果它是您要撤消它,则可以执行

\To see if user has been modified you can check if user in session.dirty. If it is and you want to undo it, you can execute

session.rollback()

,但是请注意,这会将会话的所有内容回滚到最后一个session.commit().

but be advised that this will rollback everything for the session to the last session.commit().

如果您想获取原始值,并且内存可以正确地为我服务,则它是sqlalchemy.orm.attributes.get_history实用程序函数返回的元组的第二个元素.你必须要做

If you want to get the original values and memory serves me correctly, it's the second element of the tuple returned by the sqlalchemy.orm.attributes.get_history utility function. You would have to do

old_value = sqlalchemy.orm.attributes.get_history(user, 'attribute')[2]

针对所需的每个属性.

这篇关于如何获取已更改字段的原始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆