10👍
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
7👍
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
- Celery tasks not throwing exception in Django Tests
- Is it possible to force queryset evaluation while keeping it a queryset
- Programmatically sync the db in Django
- Using an aggregate in a Django model's property