I wish to use Django REST framework to create a number of model objects "together" -- i.e. in a single transaction.
The objective is that each of the objects will only be visible at the (successful) end of the transaction.
How can I do that?
Django provides a single API to control database transactions. 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.
Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.
Use atomic
from django.db.transaction
as a decorator around a function performing the database operations you are after:
If obj_list
contains a list of populated (but not saved) model objects, this will execute all operations as part of one transaction.
@atomic
def save_multiple_objects(obj_list):
for o in obj_list:
o.save()
If you want to save multiple objects as part of the same API request, then (for example), if they are all of the same type, then you could POST a list of objects to an API endpoint - see Django REST framework post array of objects
You can achieve this by using django db transactions
. Refer to the code below
from django.db import transaction
with transaction.atomic():
model_instance = form.save(commit=False)
model_instance.creator = self.request.user
model_instance.img_field.field.upload_to = 'directory/'+model_instance.name+'/logo'
self.object = form.save()
This example is taken from my own answer to this SO post. This way, before calling save() you can save/edit other dependencies
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