如何获取更改字段的原始值? [英] How to get the original value of changed fields?
问题描述
我使用 sqlalchemy 作为我的 orm,并使用 declarative
作为 Base.
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]
对于您想要的每个属性.
for each attribute that you want.
这篇关于如何获取更改字段的原始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!