I am trying to create a view where I save an object but I'd like to undo that save if some exception is raised. This is what I tried:
class MyView(View):
@transation.atomic
def post(self, request, *args, **kwargs):
try:
some_object = SomeModel(...)
some_object.save()
if something:
raise exception.NotAcceptable()
# When the workflow comes into this condition, I think the previous save should be undome
# Whant am I missing?
except exception.NotAcceptable, e:
# do something
What am I doing wrong? even when the exception is raised some_object
is still in DataBase.
However, if an exception happens in a function decorated with transaction.atomic, then you don't have anything to do, it'll rollback automatically to the savepoint created by the decorator before running the your function, as documented:
If the exception is catched in an except block, then it should be re-raised for atomic to catch it and do the rollback, ie.:
Also, if you want more control, you can rollback manually to previously set savepoint, ie.:
Atomicity Documentation
To summarize,
@transaction.atomic
will execute a transaction on the database if your view produces a response without errors. Because you're catching the exception yourself, it appears to Django that your view executed just fine.If you catch the exception, you need to handle it yourself: Controlling Transactions
If you need to produce a proper json response in the event of failure: