PATCH method in django-rest returns 400 BAD REQUEST

為{幸葍}努か 提交于 2021-02-11 12:35:52

问题


I've been trying to setup my API to handle PATCH requests, but I keep getting the 400 BAD REQUEST response. I can't seem to figure out what I need to change in order for it to work. The get method is working the way it's supposed to, but the PATCH is evading me.

serializers.py

class HeroCounterSerializer(serializers.ModelSerializer):
    class Meta:
        model = HeroCounters
        fields = ('ct1', 'ct2', 'score', 'pk')

views.py

class HeroCounterViewSet(viewsets.ModelViewSet):

    queryset = HeroCounters.objects.all()
    serializer_class = HeroCounterSerializer

    @detail_route(methods=['GET', 'PATCH'])
    def counter_list(self, request, pk=None):

        if request.method == 'GET':
             # retrieve an object by pk provided
            hero = Hero.objects.get(pk=pk)
            herocounters = HeroCounters.objects.filter(ct1=hero).distinct().order_by('score')[:10]
            herocounters_json = HeroCounterSerializer(herocounters, many=True)
            return Response(herocounters_json.data)
        elif request.method == 'PATCH':
            instance = HeroCounters.objects.get(pk=pk)
            request.data['HeroCounters'] = HeroCounters.id

            # pass in the instance we want to update
            serializer = HeroCounterSerializer(instance, data=request.data)

            # validate and update
            if serializer.is_valid():
                serializer.save()
                serializer_dict = serializer.data
                serializer_dict["message"] = "Settings updated successfully."
                return Response(serializer_dict, status=status.HTTP_200_OK)
            else:
                return Response(serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)

回答1:


In order for a PATCH to work correctly, you have to signal to the serializer that the incoming update is partial. Hence your serializer instantiation should be:

        serializer = HeroCounterSerializer(instance, data=request.data, partial=True)


来源:https://stackoverflow.com/questions/56579415/patch-method-in-django-rest-returns-400-bad-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!