DRF更新一行

时间:2018-05-16 20:30:22

标签: python django django-rest-framework

我试图更新客户端数据库中的现有行我使用put方法向服务器发送请求我使用了updatemodelmixin也是id通过此视图服务器响应来到服务器数据

maximum recursion depth exceeded

更新数据的正确方法是什么?

class ProductOwnserSingleViewAPIView(APIView,mixins.UpdateModelMixin):

    queryset = Product.objects.all()
    serializer_class = ProductSerializer

    def put(self, request, *args, **kwargs):
        return  self.put(self,request,*kwargs,**kwargs)

    def get(self, request):
        id = request.GET.get("id")
        try:
            product = Product.objects.get(
                author_id=request.user.id,
                product_id=id
            )
            if not product:
                return Response(status.HTTP_400_BAD_REQUEST)
            serializer = ProductSerializer(instance=product, context={"request": request})
            return Response(serializer.data)
        except Product.DoesNotExist:
            return Response(status.HTTP_400_BAD_REQUEST)

2 个答案:

答案 0 :(得分:1)

你写道:

class ProductOwnserSingleViewAPIView(APIView,mixins.UpdateModelMixin):

    # ...

    def put(self, request, *args, **kwargs):
        return  self.put(self,request,*kwargs,**kwargs)

如果您执行PUT请求,则表示使用某些参数调用put(..)函数。但是你的put函数做了什么?实际上,它使用相同的参数调用本身。此调用随后导致另一个调用,因此您将一直调用,直到调用堆栈达到其最大值,并发生错误。

put(..)的典型工作流程是:

class ProductOwnserSingleViewAPIView(APIView,mixins.UpdateModelMixin):

    # ...

    def put(self, request, pk, format=None):
        # obtain the element we want to "update"
        product = Product.objects.get(
            author_id=request.user.id,
            product_id=request.GET('id')
        )

        # pass the element through the serializer with the data to update
        serializer = ProductSerializer(product, data=request.data)
        # check if the update makes sense (is valid)
        if serializer.is_valid():
            # if so, we save the object
            serializer.save()
            # and return the data as a response
            return Response(serializer.data)
        # if not, we report the errors as a response
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

所以我们首先获得我们希望PUT的元素,然后我们调用序列化器来更新我们想要更改的字段(数据在request.data中),最后是所有这些字段有效我们保存对象并返回对象的所有数据。

如果序列化程序报告错误,我们会返回这些错误。

答案 1 :(得分:0)

def put(self, request, *args, **kwargs):
    return  self.put(self,request,*kwargs,**kwargs)

改变它;

def put(self, request, *args, **kwargs):
    return  super(ProductOwnserSingleViewAPIView, self).update(request, *args, **kwargs)