Applying serializer updates to model without committing? #8570
-
Our application requires changes to certain models to be approved by users. We'd like to be able to display an accurate representation of the updates to the user. We can't just display the raw Ideally, we'd apply the change to the instance without committing it to the database. This way we can serialize it and get a true preview of the changes. A couple hacky solutions that came to mind:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I ended up going with the transaction rollback solution and it worked out surprisingly well.
Code example: from copy import copy
from django.db import transaction
class ExitTransaction(Exception):
pass
# ...
# Make a copy of the original so we can restore it later. Rolling back a
# transaction doesn't undo the changes to the instance.
original = instance.obj
instance.obj = copy(original)
try:
with transaction.atomic():
# Modify instance.obj somehow...
modify_obj(instance.obj)
# Raise an exception to rollback the transaction
raise ExitTransaction
except ExitTransaction:
pass
# instance.obj still has the modifications
updated_obj = instance.obj
# Restore the original object
instance.obj = original
# updated_obj can now be used however you need it, but just make sure not to
# call .save() or else it will actually commit the changes. |
Beta Was this translation helpful? Give feedback.
I ended up going with the transaction rollback solution and it worked out surprisingly well.
Code example: