Python 将peewee模型还原为数据库中的数据
假设我在peewee有一个模型:Python 将peewee模型还原为数据库中的数据,python,postgresql,orm,peewee,Python,Postgresql,Orm,Peewee,假设我在peewee有一个模型: class foo(Model): id = PrimaryKeyField() bar = TextField(null=True) ... 我从数据库中获取foo的一个实例: inst = foo.get(id=1) print(inst.bar) #Prints 'ValueA' 用户更改模型的值: inst.bar = 'ValueB' #inst.save() has not been called 现在,用户希望将ins
class foo(Model):
id = PrimaryKeyField()
bar = TextField(null=True)
...
我从数据库中获取foo
的一个实例:
inst = foo.get(id=1)
print(inst.bar) #Prints 'ValueA'
用户更改模型的值:
inst.bar = 'ValueB'
#inst.save() has not been called
现在,用户希望将inst
还原回数据库中当前的值。我希望做到这一点:
print(inst.bar) #Prints 'ValueB'
#Some function that reverts to the database
print(inst.bar) #'ValueA'
我看到的最接近的事情是在事务中包装修改,但不清楚需要如何包装修改。我进行了一些测试,但事务不起作用:
with database.atomic() as txn:
inst.bar = 'ValueB'
txn.rollback()
#I also tried database.rollback() and it didn't work
print(inst.bar) #'ValueB'
在事务中包装对save()
的调用,并调用rollback()
可防止修改数据库,但之后模型实例仍包含新值
如何实现预期的行为?我通过跟踪外部的任何更改,并仅在准备将更改提交到数据库时将更改应用到模型实例,间接地解决了问题。更改跟踪器的主要逻辑如下所示:
class ChangeTracker:
...
def editRow(self,model,field,value):
if model not in self.changedRows:
self.changedRows[model] = {}
self.changedRows[model][field] = value
def commitChanges(self):
for model in self.changedRows:
for field in self.changedRows[model]:
value = self.changedRows[model][field]
setattr(model,field,value)
model.save()