问题
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