Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

python - How to get the original value of changed fields?

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?

Thanks in advance!


UPDATE

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'])

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...