一、Mixin类
提供了几种后端视图(对数据资源进行增删改查)处理流程的实现,如果需要编写的视图属于这五种,则视图可以通过继承相应的扩展类来复用代码,减少自己编写的代码量。
这五个扩展类需要搭配GenericAPIView通用视图基类来开发业务接口
1、ListModelMixin
列表视图扩展类,提供 list(request, *args, **kwargs)方法快速实现列表视图,返回200状态码。
该Mixin的list方法会对数据进行过滤和分页,如果不重写过滤和分页的方法是不会进行过滤和分页的。
源码简化
classListModelMixin:deflist(self,request,*args,**kwargs):
queryset=self.get_queryset()
serializer=self.get_serializer(instance=queryset,many=True)return Response(serializer.data)
源码
classListModelMixin:"""
List a queryset.
"""deflist(self, request,*args,**kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)if page isnotNone:
serializer = self.get_serializer(page, many=True)return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)return Response(serializer.data)
2、CreateModelMixin
创建视图扩展类,提供 create(request, *args, **kwargs)方法快速实现创建资源的视图,成功返回201状态码。
如果序列化器对前端发送的数据验证失败,返回400错误;所以要对反序列化输入字段要进行验证,校验不通过提供指定的报错。
源码简化
classCreateModelMixin:defcreate(self,request,*args,**kwargs):
serializer=self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()return Response(serializer.data)
源码
classCreateModelMixin:"""
Create a model instance.
"""defcreate(self, request,*args,**kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)defperform_create(self, serializer):
serializer.save()defget_success_headers(self, data):try:return{'Location':str(data[api_settings.URL_FIELD_NAME])}except(TypeError, KeyError):return{}
3、RetrieveModelMixin
详情视图扩展类,提供 retrieve(request, *args, **kwargs)方法,可以快速实现返回一个存在的数据对象。
如果存在,返回200, 否则返回404。
源码
classRetrieveModelMixin:defretrieve(self,request,*args,**kwargs):
instance=self.get_object()
serializer=ProjectsSerializer(instance=instance)return Response(serializer.data)
4、UpdateModelMixin
更新视图扩展类,提供 update(request, *args, **kwargs)方法,可以快速实现更新一个存在的数据对象。
同时也提供 partial_update(request, *args, **kwargs)方法,可以实现局部更新。
成功返回200,序列化器校验数据失败时,返回400错误。
源码简化
classUpdateModelMixin:defupdate(self,request,*args,**kwargs):
obj=self.get_object()
serializer=ProjectsSerializer(instance=obj,data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()return Response(serializer.data)
源码
classUpdateModelMixin:"""
Update a model instance.
"""defupdate(self, request,*args,**kwargs):
partial = kwargs.pop('partial',False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)ifgetattr(instance,'_prefetched_objects_cache',None):# If 'prefetch_related' has been applied to a queryset, we need to# forcibly invalidate the prefetch cache on the instance.
instance._prefetched_objects_cache ={}return Response(serializer.data)defperform_update(self, serializer):
serializer.save()defpartial_update(self, request,*args,**kwargs):
kwargs['partial']=Truereturn self.update(request,*args,**kwargs)
5、DestroyModelMixin
删除视图扩展类,提供 destroy(request, *args, **kwargs)方法,可以快速实现删除一个存在的数据对象。
成功返回204,不存在返回404。
源码简化
classDestroyModelMixindefdestroy(self,request,*args,**kwargs):
obj=self.get_object()
obj.delete()return Response({'msg':'删除数据成功'},status=204)
源码
classDestroyModelMixin:"""
Destroy a model instance.
"""defdestroy(self, request,*args,**kwargs):
instance = self.get_object()
self.perform_destroy(instance)return Response(status=status.HTTP_204_NO_CONTENT)defperform_destroy(self, instance):
instance.delete()
二、GenericAPIView的视图子类
1、CreateAPIView
提供post方法
继承关系:CreateModelMixin、GenericAPIView
使用:基本属性定义:queryset、serializer_class
classCreateAPIView(mixins.CreateModelMixin,
GenericAPIView):"""
Concrete view for creating a model instance.
"""defpost(self, request,*args,**kwargs):return self.create(request,*args,**kwargs)
2、ListAPIView
提供get方法
继承关系:ListModelMixin、GenericAPIView
使用:基本属性定义:queryset、serializer_class
classListAPIView(mixins.ListModelMixin,
GenericAPIView):"""
Concrete view for listing a queryset.
"""defget(self, request,*args,**kwargs):return self.list(request,*args,**kwargs)
3、RetrieveAPIView
提供get方法
继承关系:RetrieveModelMixin、GenericAPIView
使用:基本属性定义:queryset、serializer_class
classRetrieveAPIView(mixins.RetrieveModelMixin,
GenericAPIView):"""
Concrete view for retrieving a model instance.
"""defget(self, request,*args,**kwargs):return self.retrieve(request,*args,**kwargs)
4、UpdateAPIView
提供put、patch方法
继承关系:UpdateModelMixin、GenericAPIView
使用:基本属性定义:queryset、serializer_class
classUpdateAPIView(mixins.UpdateModelMixin,
GenericAPIView):"""
Concrete view for updating a model instance.
"""defput(self, request,*args,**kwargs):return self.update(request,*args,**kwargs)defpatch(self, request,*args,**kwargs):return self.partial_update(request,*args,**kwargs)
5、DestoryAPIView
提供delete方法
继承关系:DestoryModelMixin、GenericAPIView
使用:基本属性定义:queryset、serializer_class
classDestroyAPIView(mixins.DestroyModelMixin,
GenericAPIView):"""
Concrete view for deleting a model instance.
"""defdelete(self, request,*args,**kwargs):return self.destroy(request,*args,**kwargs)
6、ListCreateAPIView
提供get、post方法
继承关系:ListModelMixin、CreateModelMixin、GenericAPIView
使用:基本属性定义:queryset、serializer_class
classListCreateAPIView(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericAPIView):"""
Concrete view for listing a queryset or creating a model instance.
"""defget(self, request,*args,**kwargs):return self.list(request,*args,**kwargs)defpost(self, request,*args,**kwargs):return self.create(request,*args,**kwargs)
7、RetrieveUpdateAPIView
提供get、put、patch方法
继承关系:RetrieveModelMixin、UpdateModelMixin、GenericAPIView
使用:基本属性定义:queryset、serializer_class
classRetrieveUpdateAPIView(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
GenericAPIView):"""
Concrete view for retrieving, updating a model instance.
"""defget(self, request,*args,**kwargs):return self.retrieve(request,*args,**kwargs)defput(self, request,*args,**kwargs):return self.update(request,*args,**kwargs)defpatch(self, request,*args,**kwargs):return self.partial_update(request,*args`
8、RetrieveDestoryAPIView
提供get、delete方法
继承关系:RetrieveModelMixin、DestoryModelMixin、GenericAPIView
使用:基本属性定义:queryset、serializer_class
classRetrieveDestroyAPIView(mixins.RetrieveModelMixin,
mixins.DestroyModelMixin,
GenericAPIView):"""
Concrete view for retrieving or deleting a model instance.
"""defget(self, request,*args,**kwargs):return self.retrieve(request,*args,**kwargs)defdelete(self, request,*args,**kwargs):return self.destroy(request,*args,**kwargs)
9、RetrieveUpdateDestoryAPIView
提供get、put、patch、delete方法
继承关系:RetrieveModelMixin、UpdateModelMixin、DestoryModelMixin、GenericAPIView
使用:基本属性定义:queryset、serializer_class
classRetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
GenericAPIView):"""
Concrete view for retrieving, updating or deleting a model instance.
"""defget(self, request,*args,**kwargs):return self.retrieve(request,*args,**kwargs)defput(self, request,*args,**kwargs):return self.update(request,*args,**kwargs)defpatch(self, request,*args,**kwargs):return self.partial_update(request,*args,**kwargs)defdelete(self, request,*args,**kwargs):return self.destroy(request,*args,**kwargs)
版权归原作者 敲代码敲到头发茂密 所有, 如有侵权,请联系我们删除。