Perhaps in Django there is a way to do a rollback in case of failure of transactions such as insert, update, delete, that is, normally the code to insert would be something like this:
nuevo_elemento = MiModelo(
elemento1 = valor1,
elemento2 = valor2,
...
...
etc
)
nuevo_elemento.save()
Well, this basically creates or saves an element in Django, but what if this goes in a loop:
for item in list_productos:
nuevo_producto = Producto(
elemento1 = item
...
)
nuevo_producto.save()
And when executing this it inserts several of them but due to some mishap or error it did not insert all the elements of the list_productos
, how do I do that rollback thus avoiding inserting a few and not all the required ones.
By default, Django works in autocommit mode , which means that every time you make a query it is immediately sent to the database. What you need to do is control transactions explicitly to ensure the atomicity of a function or a block of code, that is, that all the queries that are executed within a block of code are all (if all went well) or nothing ( if an error occurred in the process, a rollback is made).
For this you have two options.
Declare a function as atomic using a decorator:
Per code block using a context manager: