django-rest中的PATCH方法返回400错误请求 [英] PATCH method in django-rest returns 400 BAD REQUEST
本文介绍了django-rest中的PATCH方法返回400错误请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试设置我的API以处理PATCH请求,但是我一直收到400 BAD REQUEST响应.我似乎无法弄清楚我需要进行哪些更改才能使其正常工作.get方法可以按预期的方式工作,但是PATCH在逃避我.
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)
推荐答案
为使 PATCH
正常工作,您必须向序列化器发送信号,告知传入的更新为
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)
这篇关于django-rest中的PATCH方法返回400错误请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文