3

settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'diva',
    'USER': 'root',
    'PASSWORD': 'admin',
    'ATOMIC_REQUESTS':True,
    'HOST': 'localhost',
    'PORT': '3306',
},

}

views.py

def create_project(self, request):
    try:
        with transaction.atomic():
               code here
    except Exception as e:
        print "Exception--->",str(e)
        response = {"status":"failed",'response': ugettext("projects.services.create_project.failure")}
        stat = status.HTTP_400_BAD_REQUEST
        return Response(response, status=stat)

in my code, if it raises ObjectDoesNotExist Exception rollback is not happening, can anyone explain how transactions work in django with example.

1 Answers1

5

This is the correct. Behaviour django will rollback a transaction, if an exception occurs but that exeption has to be a DatabaseError or one of it's subclasses (most notably IntegrityError)

The ObjectDoesNotExist is not a subclass of DatabaseError and as such there is no reason for this transaction to be rolled back.

last but not least. Don't catch Exception always catch the specific exception that you are looking out for.

e4c5
  • 52,766
  • 11
  • 101
  • 134
  • Ouch! I'm glad I read this before I got bitten. Anyone know, why Django persists DB changes in this circumstance? – nigel222 Mar 22 '17 at 09:07
  • Thank you for your explanation @e4c5. I need to rollback the entire transaction if any exception raised in my code and also able to send my own response from the view. How can i achieve that? – Ramachandraiah Putta Mar 22 '17 at 09:39
  • Sorry I seemed to have missed your comment. Just ran across this when going through some old answers. Do you still need help or is this sorted out? – e4c5 May 07 '17 at 04:59