Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use transactions with Django REST framework?

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?

like image 763
Ben RR Avatar asked Oct 13 '16 11:10

Ben RR


People also ask

How do Django transactions work?

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.

Is Django GOOD FOR REST API?

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.


2 Answers

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

like image 51
Jonathan Windridge Avatar answered Oct 02 '22 14:10

Jonathan Windridge


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

like image 22
cutteeth Avatar answered Sep 30 '22 14:09

cutteeth