Ben RR
Ben RR

Reputation: 943

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?

Upvotes: 12

Views: 10379

Answers (2)

cutteeth
cutteeth

Reputation: 2213

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

Upvotes: 7

Jonathan Windridge
Jonathan Windridge

Reputation: 407

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

Upvotes: 11

Related Questions