How To Do To A Manual Commit Using Django
Solution 1:
It's not possible to manually commit or rollback the transaction inside an atomic block.
Instead, you can raise an exception inside the atomic block. If the block completes, the transaction will be committed. If you raise an exception, the transaction will be rolled back. Outside the atomic block, you can catch the exception and carry on your view.
try:
with transaction.atomic():
do_stuff()
if ok_to_commit():
passelse:
raise ValueError()
except ValueError:
pass
Solution 2:
I think you should give the Django documentation about db transactions another look.
The most relevant remark is the following:
Avoid catching exceptions inside atomic!
When exiting an atomic block, Django looks at whether it’s exited normally or with an exception to determine whether to commit or roll back. If you catch and handle exceptions inside an atomic block, you may hide from Django the fact that a problem has happened. This can result in unexpected behavior.
Adapting the example from the docs, it looks like you should nest your try
and with
blocks like this:
@transaction.atomicdefupdate_user_groups(request):
# set your variablestry:
with transaction.atomic():
# do your for loopif count < 1:
# You should probably make a more descriptive, non-generic exception# see http://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python for more inforaise Exception('Count is less than one')
except:
handle_exception()
Post a Comment for "How To Do To A Manual Commit Using Django"