django-rest-framework:无法调用`.is_valid()`,因为在实例化序列化程序实例时未传递`data =`关键字参数 [英] django-rest-framework: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance

查看:1468
本文介绍了django-rest-framework:无法调用`.is_valid()`,因为在实例化序列化程序实例时未传递`data =`关键字参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型:

class NoteCategory(models.Model):
    title = models.CharField(max_length=100, unique=True)

    def __unicode__(self):
        return '{}'.format(self.title)

class PatientNote(models.Model):
    category = models.ForeignKey(NoteCategory)
    patient = models.ForeignKey(Patient)
    description = models.CharField(max_length=500)
    created_at = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return '{}'.format(self.description)

以及以下序列化器:

class PatientNoteSerializer(serializers.ModelSerializer):
    class Meta:
        model = PatientNote

我只想在PatientNote上进行POST. GET可以正常工作,其他型号的POST也可以正常工作:

I just want to make a POST on the PatientNote. The GET works and also the POST on other models works properly:

class PatientNoteViewSet(APIView):
    queryset = PatientNote.objects.all()


    def post(self, request, format=None):
        if not request.auth:
            return Response({})
        token = Token.objects.filter(key=request.auth)[0]
        user = token.user

        serializer = PatientNoteSerializer(request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

request.data是QueryDict,即

The request.data is a QueryDict, i.e.,

<QueryDict: {u'category': [u'1'], u'patient': [u'1'], u'description': [u'da rest']}>

它将能够通过它们的ID填充两个FK(患者和类别),并且描述是简单的文本.

It would be able to populate the two FKs, patient and category, through their IDs and the description is a simple text.

POST请求是以下请求(与其他模型一起使用):

The POST request is the following one (that works with other models):

无论如何,POST响应为500,出现以下错误:

Anyway, the POST response is 500 with the following error:

AssertionError at /api/notes/

由于实例化序列化程序实例时未传递data=关键字参数,因此无法调用.is_valid().

Cannot call .is_valid() as no data= keyword argument was passed when instantiating the serializer instance.

如果我尝试在python shell中使用它,则错误是相同的.

The error is the same if I try to use it in the python shell.

推荐答案

要序列化对象时,请将对象作为第一个参数传递.

When you want to serialize objects, you pass object as a first argument.

serializer = CommentSerializer(comment)
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}

但是,当您想反序列化时,可以使用data kwarg传递数据.

But when you want to deserialize you pass the data with a data kwarg.

serializer = CommentSerializer(data=data)
serializer.is_valid()
# True
serializer.validated_data
# {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}

因此,在您的情况下,您想反序列化您的帖子数据,因此您必须这样做:

So in your case you want to deserialize your post data, therefor you have to do:

serializer = PatientNoteSerializer(data=request.data)

这篇关于django-rest-framework:无法调用`.is_valid()`,因为在实例化序列化程序实例时未传递`data =`关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆