Abz Rockers Abz Rockers - 6 days ago 5
Python Question

transaction based in django

I would like to get some idea on how to improve (if any) my code in implementing transaction based query in Django.

This is how I understand the ATOMIC_REQUEST I read on django documentation. I have this function view:

from django.db import transaction
import sys
@transaction.atomic
def save_progress(request):
try:
with atomic.transaction():
qs = AllProgressModel()
qs.name = 'level up'
qs.level = 25
qs.description = 'Increased 2 level'
qs.save()
except:
print(sys.exc_info())


-Am I doing it right?

-Is the progress will be saved or not if the connection lost occur during saving?

Thank you in advance!

Answer

You don't need both decorator @transaction.atomic and with atomic.transaction(), one is usually enough.

While using with atomic.transaction(), catch IntegrityError exceptions instead of broadly handling all exceptions at once.

Edit: If you're handling exceptions outside the atomic block (like below) then it's a better practice to have an outer atomic wrap as well, for handling rollbacks and other database operations you might need in exception handling part.

def save_progress(request):
   try:
       with atomic.transaction():
           ...
           qs.name = 'level up'
           qs.level = 25
           qs.description = 'Increased 2 level'
           qs.save()
   except IntegrityError:
       # You are here if something goes within the transaction, after rollback
       # HANDLE exception
Comments