序列化器.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 运行

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

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

每次它进入其他部分。

请高手帮忙

最佳答案

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

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

文档 link

关于python - PUT 请求在字段重命名时失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39328384/

10-15 00:12