PUT请求在字段重命名时失败

时间:2016-09-05 10:14:04

标签: python django django-rest-framework

Serializer.py

class CategorySerializer(serializers.ModelSerializer) :
    id = serializers.IntegerField(source='category_id')
    name = serializers.CharField(source='category_name')

    class Meta:
        model = Category
        fields = ['id', 'name']

上面的GET工作正常,但是当我运行PUT请求时,它会进入失败块

PUT的views.py

request.method == 'PUT':
        serializer = CategorySerializer(category, data=request.data)
        if serializer.is_valid():
            serializer.save()
            response = {
                'status': status.HTTP_200_OK,
                'message' : "Category Updated",
            }
            return HttpResponse(json.dumps(response), content_type='application/json')
        else :
            response = {
                'status': status.HTTP_400_BAD_REQUEST,
                'message' : "Category not found",
            }
            return HttpResponse(json.dumps(response), content_type='application/json')

我正在追踪卷曲

curl -X PUT http://localhost:8000/api/add-category/4/ -d" category_name = xyz"

响应:

{"status": 400, "message": "Category not found"}

每次进入其他部分。

专家请帮忙

2 个答案:

答案 0 :(得分:2)

您没有附加序列化程序错误,但看起来您应该为partial请求方法设置PUT参数。 试试

serializer = CategorySerializer(category, data=request.data, partial=True)

文档link

答案 1 :(得分:0)

我认为id字段存在问题,这是必需的。但是您只发送了name字段,请尝试使用partial密钥。

serializer = CategorySerializer(category, data=request.data, partial=True)