django rest_framework 错误信息 AssertionError: When a serializer is passed a `data` keyword

今天在学习django 的rest_framework规范时,遇到了 AssertionError: When a serializer is passed a `data` keyword argument you must call `.is_valid()` before attempting to access the serialized `.data` representation. 错误信息。记录一下解决方法。

错误代码:

class BookModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Books
        fields = "__all__"


class BooksView(APIView):
    def get(self, request):
        book_list = Books.objects.all()
        ret = BookModelSerializer(book_list, many=True)
        return Response(ret.data)

    def post(self, request):
        print(request.data)
        bs = BookModelSerializer(data=request.data)
        print(bs.data)
        if bs.is_valid():
            return Response(bs.data)

        else:
            return Response(bs.errors)

错误原因:

首先在将序列化的数据反序列化成对象时,要在序列化类的参数中指明data=序列化的数据

在调用对象.data时,要先执行.is_valid()方法后,才能调用

所以修改成下面这样就不报错了

class BookModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Books
        fields = "__all__"


class BooksView(APIView):
    def get(self, request):
        book_list = Books.objects.all()
        ret = BookModelSerializer(book_list, many=True)
        return Response(ret.data)

    def post(self, request):
        print(request.data)
        bs = BookModelSerializer(data=request.data)
        if bs.is_valid():
            print(bs.data)
            return Response(bs.data)

        else:
            return Response(bs.errors)

 

你可能感兴趣的:(那些坑)