Lelouch
Lelouch

Reputation: 2193

Django REST framework save()

When deserializing data with keyword argument many=True

serialized = MySerializer(data=request.data, many=True)

and then call .save(), I wonder if it is performing one database operation, or just iterating the list of sub-data, and perform create() and update() individually?

Upvotes: 0

Views: 1274

Answers (2)

Kevin Brown-Silva
Kevin Brown-Silva

Reputation: 41671

This is a place where I always recommend looking at the code itself as it will always provide the most up-to-date answer. Currently the default create code for a ListSerializer is

def create(self, validated_data):
    return [
        self.child.create(attrs) for attrs in validated_data
    ]

The answer is that it will manually call create for each object, which means that it is not performing a bulk insert. Part of this comes from the fact that Django REST Framework is not designed to work efficiently with large amounts of data, with the exception of displaying it. It also does not support bulk updates by default.


You can find more information on the default bulk creation in the documentation, as well as help on creating your own bulk update methods as well. This will require you to create your own custom ListSerializer with your own create and update methods that do what you are looking for. Keep in mind that a ListSerializer is what Django REST Framework internally wraps your many=True serializer with, which you can see by calling repr(serializer) where serializer is your serializer that you have initialized with many=True.


In the past, bulk updates have been handled by a third-party package called Django REST Framework Bulk. While the package works with DRF 2.x, it is in the process of being updated for 3.0. There is a pull request that is currently under review for adding 3.0 support, so I would expect there to be a new release soon that adds support.

Upvotes: 1

justcompile
justcompile

Reputation: 3542

According to the documentation, it will make one call per object in the collection, but you can override this behaviour:

http://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-create

Upvotes: 1

Related Questions