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
qs = AllProgressModel()
qs.name = 'level up'
qs.level = 25
qs.description = 'Increased 2 level'
You don't need both decorator
with atomic.transaction(), one is usually enough.
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