Django REST:CREATE函数不在serialize类中调用

时间:2015-07-23 14:03:29

标签: django django-rest-framework

问题是创建函数没有调用,只是返回验证布尔值,无论是 true还是false 请注意:验证部分工作正常。

代码如下:

Views.py

class TestAPI(APIView):
    serializer_request = TestAPISerializer

    def post(self,request):     
        obj = self.serializer_request(data=request.data)
        print obj.is_valid()
        if obj.is_valid():
            obj.save()
            return Response(status=status.HTTP_200_OK)
        else:
            return Response(request_for_demo_ser.errors, status=status.HTTP_400_BAD_REQUEST)

Serializers.py

class TestAPISerializer(serializers.ModelSerializer):
    class Meta:
        model = TestDemo
        fields = ('name')

    # THIS FUNCTION IS NOT AT ALL CALLING. 
    def create(self, validated_data):
        name = validated_data['name'] 
        return TestDemo.objects.create(name=name)

1 个答案:

答案 0 :(得分:1)

你忘了保存。

obj = self.serializer_request(data=request.data)
print obj.is_valid()
if obj.is_valid():        
    obj.save()  # add this line
    # Change code to 201
    return Response(status=status.HTTP_201_CREATED)
    # return Response(status=status.HTTP_200_OK)