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".
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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With