我的 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
我正在我的 Django 测试套件上试验它:
def test_file_post(self):
request = self.factory.post('/path/file_query', {"many":False})
request.data = {
... # omitted fields here
}
response = FileQuery.as_view()(request)
它打印I am creating multiple rows!,这是不应该发生的事情。
根据 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.
所以我不明白什么?我在发布请求中传入了 many:False,但它仍然将 create 函数委托(delegate)给 FileListSerializer!
请您参考如下方法:
根据文档:
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
您可以将 many=True 添加到您的序列化程序
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? 的潜在骗局
