29

In my view, I am saving data in multiple models:

def myview(request):
    #do some processing
    model1.save()
    model2.save()

How do I ensure that there is a rollback of model1.save() in case model2.save() raises an error? Or how do I commit only after both the models are successfully saved?

In other words, "only save model1 and model2 if both save() are successful", or "perform both saves inside a transaction".

2 Answers 2

60

Use an atomic transaction:

Atomicity is the defining property of database transactions. atomic allows us to create a block of code within which the atomicity on the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.

Examples:

from django.db import transaction

with transaction.atomic():
    model1.save()
    model2.save()

and

from django.db import transaction, IntegrityError

try:
    with transaction.atomic():
        model1.save()
        model2.save()
except IntegrityError:
    handle_exception()
1
  • 1
    import transaction should be : from django.db import transaction
    – jnvilo
    Commented Feb 7, 2017 at 14:54
3

Alternative solution using a decorator:

from django.db import transaction

@transaction.atomic
def myview(request):
    # This code executes inside a transaction.
    model1.save()
    model2.save()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.