gpt4 book ai didi

Django Rest框架批量创建

转载 作者:行者123 更新时间:2023-12-02 23:03:44 25 4
gpt4 key购买 nike

我正在尝试创建一个 API,您可以使用 django Rest 框架通过单个 Post 请求创建多个对象。但是,我的序列化器提供了一个我不明白的错误。首先这是我的代码的骨架

我的序列化器:

class MyModelSerializer(serializers.ModelSerializer):
# override the constructor to always use the many flag
def __init__(self, *args, **kwargs):
many = kwargs.pop('many', True)
super(MyModelSerializer, self).__init__(many=many, *args, **kwargs)

class Meta:
model = MyModel
fields = ('field1', 'field2')

我的 ListView

class MyModelListView(generics.ListCreateAPIView):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer

def post(self, request, *args, **kwargs):
if request.DATA['batch']:
json = request.DATA['batchData']
stream = StringIO(json)
data = JSONParser().parse(stream)
request._data = data
return super(CharacterDatumList, self).post(request, *args, **kwargs)

我的ajax调用

$.ajax({
type: "POST",
url: '/characterDatum/',
data: {
'batch' : true,
'batchData' : '[{"field1": "x", "field2": "y", },{"field1": "a", "field2": "b"}]'
},
success: function(response) {
console.log('success');
},
datatype: 'json'
});

但是,在 django Rest 框架中,我在下面的行中收到序列化验证错误

class CreateModelMixin(object):
"""
Create a model instance.
"""
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.DATA, files=request.FILES)
if serializer.is_valid(): # returns not valid

有谁知道为什么会出现这种情况吗?

最佳答案

我找到了!序列化器实际上并未使用 Many 选项,因此我必须重写 MyModelListView 中的 get_serializer 方法

def get_serializer(self, instance=None, data=None,
files=None, many=True, partial=False):
return super(MyModelListView, self).get_serializer(instance, data, files, many, partial)

关于Django Rest框架批量创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21439672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com