Django REST Framework: Multiple Objects Creation

Django REST Framework: Multiple Objects Creation

Official Django rest framework logo

Let’s say we have a requirement to create multiple instances in one Django API.

For example, consider a Django model:

Django model codeshot

Django model codeshot

Where a trader submits rate on date basis for a particular item. He does, on a mobile interface.

It is preferred by mobile teams that this process of submission is done in 1 API call, rather than multiple, where each time trader submits, create API is called.

In the latter case, if we have 100 items for 1000 users, then we have 100 x 1000 = 100000 requests: are quick but plenty server hits. Mobile development would prefer the former case.

To achieve the former, we need something like this.

Model viewset codeshot

Model viewset codeshot

The points: Above is

  1. More Pythonic: Request body shall contain a list of the dictionary of ItemRate attributes and each dictionary is processed one a time using the for-loop.
  2. Less Friendly: Suppose that the first and third dictionary contains invalid data. After calling the API, in the error response, we get error details only for the first dictionary, as code has evaluated only the first dictionary and yet to reach the third dictionary.

A possible solution is to use the serializer effectively.

Like this,

Decorator action in model viewset

Decorator action in model viewset

Is a simple workaround, where many=True is added to__the serializer.

Here serializer creates either all objects or none but gives out dictionary wise error details.

[## aravindas4/django-shots1

Contribute to aravindas4/django-shots1 development by creating an account on GitHub.

github.com](https://github.com/aravindas4/django-shots1/tree/master/app2)