我一直在尝试设置我的API以处理PATCH请求,但是我一直收到400 BAD REQUEST响应。我似乎无法弄清楚需要什么才能使其正常工作。 get方法可以按预期的方式运行,但是PATCH却在逃避我。
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)
答案 0 :(得分:2)
为了使for releaseGroup in releaseGroups {
let rg = ReleaseGroup.init(id: releaseGroup.id, externalServiceID: releaseGroup.externalServiceID, title: releaseGroup.title, externalServiceImageURL: releaseGroup.externalServiceImageURL, type: releaseGroup.type)
self.releaseGroups.append(rg)
}
正常工作,您必须向串行器发出进入更新为partial
的信号。因此,您的序列化程序实例应为:
PATCH