Reputation: 3968
I have the following code for my serializers.py
:
from rest_framework import serializers
from django.db import transaction
from secdata_finder.models import File
class FileListSerializer(serializers.ListSerializer):
@transaction.atomic
def batch_save_files(file_data):
files = [File(**data) for data in file_data]
return File.objects.bulk_create(files)
def create(self, validated_data):
print("I am creating multiple rows!")
return self.batch_save_files(validated_data)
class FileSerializer(serializers.ModelSerializer):
class Meta:
list_serializer_class = FileListSerializer
model = File
fields = (...) # omitted
I'm experimenting with it on my Django test suite:
def test_file_post(self):
request = self.factory.post('/path/file_query', {"many":False})
request.data = {
... # omitted fields here
}
response = FileQuery.as_view()(request)
It prints I am creating multiple rows!
, which is not what should happen.
Per the docs:
... customize the create or update behavior of multiple objects. For these cases you can modify the class that is used when many=True is passed, by using the list_serializer_class option on the serializer Meta class.
So what am I not understanding? I passed in many:False
in my post request, and yet it still delegates the create
function to the FileListSerializer
!
Upvotes: 3
Views: 2708
Reputation: 151
Per the docs:
The ListSerializer class provides the behavior for serializing and validating multiple objects at once. You won't typically need to use ListSerializer directly, but should instead simply pass many=True when instantiating a serializer
You can add many=True
to your serializer
class FileSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
kwargs['many'] = kwargs.get('many', True)
super().__init__(*args, **kwargs)
Potential dupe of How do I create multiple model instances with Django Rest Framework?
Upvotes: 3