How to use transactions with Django REST framework?
<p>I wish to use Django REST framework to create a number of model objects "together" -- i.e. in a single transaction. </p>

<p>The objective is that each of the objects will only be visible at the (successful) end of the transaction.</p>

<p>How can I do that?</p>

<p>You can achieve this by using <code>django db transactions</code>. Refer to the code below</p>

<pre><code>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()
</code></pre>

<p>This example is taken from my own answer to this <a href="http://stackoverflow.com/questions/11796383/django-set-the-upload-to-in-the-view/40018311#40018311">SO post</a>. This way, <code>before calling save() you can save/edit other dependencies</code></p>

python django rest django-models django-rest-framework