首页 > 解决方案 > 'GenericApiView' 对象在我的views.py 文件中没有属性'update'

问题描述

.update 函数在我的 view.py 文件中不支持这个 genericApiView,它给了我一条错误消息 'GenericApiView' object has no attribute 'update' 。

class GenericApiView(generics.GenericAPIView,mixins.ListModelMixin,
           mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.DestroyModelMixin):
    serializer_class=ArticleSerializer
    queryset=Article.objects.all()
    lookup_field='id'
    authentication_classes=[SessionAuthentication,BaseAuthentication]
    permission_classes=[IsAuthenticated]

    def get(self,request, id=None):
        if id:
            return self.retrieve(request)
        else:
            return  self.list(request)

    def post(self,request,id):
        return self.create(request,id)
# Error in this function 
    def put(self,request,id):
        return self.update(request,id)    

    def delete(self,request,id=None):
        return self.destroy(request,id)

标签: pythondjango

解决方案


您的GenericApiView类没有继承自mixins.UpdateModelMixin,并且当put方法调用时self.update()它会导致AttributeError. 可能的解决方案:

class GenericApiView(generics.GenericAPIView,
                     mixins.ListModelMixin,
                     mixins.CreateModelMixin,
                     mixins.RetrieveModelMixin,
                     mixins.DestroyModelMixin,
                     mixins.UpdateModelMixin):  # added the mixin
    # ...

推荐阅读