Python – ListSerializer in Django Restful – When is it called?

ListSerializer in Django Restful – When is it called?… here is a solution to the problem.

ListSerializer in Django Restful – When is it called?

My serializers.py has the following code:

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 something that shouldn’t happen.

According to 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 I don’t understand what? I passed many:False in the publish request, but it still delegates the create function to FileListSerializer!

Solution

According to the documentation:

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)

How do I create multiple model instances with Django Rest Framework? Potential scams

Related Problems and Solutions