Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save multiple django models in a single transaction?

Tags:

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".

like image 532
The Wanderer Avatar asked Aug 07 '15 21:08

The Wanderer


People also ask

How do I save multiple items in Django?

To create multiple records based on a Django model you can use the built-in bulk_create() method. The advantage of the bulk_create() method is that it creates all entries in a single query, so it's very efficient if you have a list of a dozen or a hundred entries you wish to create.

How can I have multiple models in a single Django Modelform?

In a nutshell: Make a form for each model, submit them both to template in a single <form> , using prefix keyarg and have the view handle validation. If there is dependency, just make sure you save the "parent" model before dependant, and use parent's ID for foreign key before commiting save of "child" model.

How do I save models in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

What is super save in Django?

When you overwrite a function (of a class) you can call the function of the parent class using super . The save function in the models records the instance in the database. The first super(Review, self). save() is to obtain an id since it is generated automatically when an instance is saved in the database.


1 Answers

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() 
like image 104
Leistungsabfall Avatar answered Oct 21 '22 07:10

Leistungsabfall