如何在使用@detail_route时更新条目?

时间:2018-03-31 00:18:48

标签: python django django-rest-framework

使用@detail_route时如何更新模型?

请参阅下面的代码,该代码适用于POST,但不适用于PATCH。如果我发送PATCH请求,则会创建一个新条目,即它发布。

class Company(models.Model):
    title = models.CharField(max_length=50)
    type = models.CharField(max_length=3)


class CompanySerializer(serializers.ModelSerializer):

    class Meta:
        model = Company
        fields = ('id', 'title', 'type')


class CompanyViewSet(viewsets.ModelViewSet):
    queryset = Company.objects.all()
    serializer_class = CompanySerializer
    filter_fields = ('id', 'type',)

    def get_serializer_class(self, data=None, request=None):

        return CompanySerializer(data=data, context={'request': self.request}, partial=True)

    @detail_route(methods=['post', 'patch'], url_path='private') 
    def private_company(self, request, version, pk=None):
        serializer = self.get_serializer_class(request.data, self.request)
        serializer.is_valid(request)
        serializer.save()
        return Response(data=serializer.data, status=status.HTTP_201_CREATED)   # <<== What do I need to do an update?

1 个答案:

答案 0 :(得分:1)

private_company()更改为以下

@detail_route(methods=['post', 'patch'], url_path='private')
def private_company(self, request, version, pk=None):
    if request.method == 'PATCH':
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(data={"status": "updated", "data": serializer.data})
    else:
        do
        something else with POST request if needed