How to save multiple Django models in one transaction?

In my opinion, I save data in several models:

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

How can I ensure rollback of model1.save() if model2.save() throws an error? Or how to make a commit only after successfully saving both models?

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

+13
source share
1 answer

Use atomic transaction :

Atomicity is the defining property of database transactions. atomic allows us to create a block of code that guarantees atomicity in the database. If the code block completes successfully, the changes are bound 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 try: with transaction.atomic(): model1.save() model2.save() except IntegrityError: handle_exception() 
+28
source

All Articles