django: Proper way to recover from IntegrityError django: Proper way to recover from IntegrityError django django

django: Proper way to recover from IntegrityError


Django's default commit mode is AutoCommit. In order to do rollback, you need to wrap the code doing the work in a transaction. [docs]

with transaction.commit_on_success():    # Your code here. Errors will auto-rollback.

To get database level autocommit, you will require the following option in your DATABASES settings dictionary.

'OPTIONS': {'autocommit': True,}

Alternately, you can use explicit savepoints to roll back to. [docs]

@transaction.commit_manuallydef viewfunc(request):  a.save()  # open transaction now contains a.save()  sid = transaction.savepoint()  b.save()  # open transaction now contains a.save() and b.save()  if want_to_keep_b:      transaction.savepoint_commit(sid)      # open transaction still contains a.save() and b.save()  else:      transaction.savepoint_rollback(sid)      # open transaction now contains only a.save()  transaction.commit()