gpt4 book ai didi

django - Django Rest Framework批量创建

转载 作者:行者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')


我的列表视图

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 - Django Rest Framework批量创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21439672/

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