Reputation: 1433
Let's say that I have a model in peewee:
class foo(Model):
id = PrimaryKeyField()
bar = TextField(null=True)
...
I get an instance of foo
from the database:
inst = foo.get(id=1)
print(inst.bar) #Prints 'ValueA'
The user changes the model's value:
inst.bar = 'ValueB'
#inst.save() has not been called
Now the user wants to revert inst
back to the value that's currently in the database. I would like to accomplish this:
print(inst.bar) #Prints 'ValueB'
#Some function that reverts to the database
print(inst.bar) #'ValueA'
The closest thing I saw is wrapping modifications in a transaction, but it is unclear how the modifications need to be wrapped. I tested a bit and transactions don't work:
with database.atomic() as txn:
inst.bar = 'ValueB'
txn.rollback()
#I also tried database.rollback() and it didn't work
print(inst.bar) #'ValueB'
Wrapping the call to save()
in a transaction and calling rollback()
prevents the database from being modified, but the model instance still contains the new value afterward.
How would I achieve my intended behavior?
Upvotes: 0
Views: 191
Reputation: 1433
I solved my problem indirectly by keeping track of any changes externally and only applying them to the model instance when ready to commit changes to the database. The main logic of the change tracker looks like this:
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()
Upvotes: 1