view:视图
generics:工具视图
mixins:视图工具集
viewsets:视图集
学习曲线: APIView => GenericAPIView => mixins的五大工具类 => generics中的工具视图 => viewsets中的视图集
一.GenericAPIView基类
# GenericAPIView是继承APIView的,完全兼容APIView # 重点:GenericAPIView在APIView基础上完成了哪些事? 1)get_queryset():从类属性queryset中获得model的queryset数据 2)get_object():从类属性queryset中获得model的queryset数据,再通过有名分组pk确定唯一操作对象 3)get_serializer():从类属性serializer_class中获得serializer的序列化类
-
路由层
urlpatterns = [ url(r‘^v2/books/$‘, views.BookGenericAPIView.as_view()), url(r‘^v2/books/(?P<pk>.*)/$‘, views.BookGenericAPIView.as_view()), ] # BookGenericAPIView.as_view() => 调用的是APIView的as_view() => View的as_view() => APIView的dispatch完成分发
-
视图层
from rest_framework.generics import GenericAPIView # BookGenericAPIView.as_view() => 调用的是APIView的as_view() => View的as_view() => APIView的dispatch完成分发 class BookGenericAPIView(GenericAPIView): queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer lookup_field = ‘pk‘ # 单查是要指定lookup_field = ‘pk‘属性 # 群查: def get(self, request, *args, **kwargs): book_query = self.get_queryset() # 会自动将queryset传入,得到model类的queryset对象 book_ser = self.get_serializer(book_query, many=True) # 等同于BookModelSerializer序列化 book_data = book_ser.data return APIResponse(results=book_data) # 单查: def get(self, request, *args, **kwargs): book_obj = self.get_object() # 会自动将queryset传入,并调用lookup_field属性,得到model类的具体的一条记录(即:对象) book_ser = self.get_serializer(book_obj) book_data = book_ser.data return APIResponse(results=book_data)
二.mixins视图工具集 - 辅助GenericAPIView
# 1)mixins有五个工具类文件,一共提供了五个工具类,六个工具方法:单查、群查、单增、单删、单整体改、单局部改 - 群查 ListModelMixin | list() - 单查 RetrieveModelMixin | retrieve() - 单增 CreateModelMixin | create() - UpdateModelMixin | update()单整体改 | partial_update()单局部改(单删:改字段) - DestroyModelMixin | destroy() 单删 注意:从数据库中删除,一般不用 # 2)继承工具类可以简化请求函数的实现体,但是必须继承GenericAPIView,需要GenericAPIView类提供的几个类属性和方法(见上方GenericAPIView基类知识点) 属性: - queryset | model类对象 - serializer_class | 序列化类 - lookup_field | 指定pk 方法: - get_queryset() | 拿到对象们 - get_object() | 拿到具体的对象 - get_serializer() | 序列化,反序列化 # 3)工具类的工具方法返回值都是Response类型对象,如果要格式化数据格式再返回给前台,可以通过 response.data 拿到工具方法返回的Response类型对象的响应数据
-
路由层
urlpatterns = [ url(r‘^v3/books/$‘, views.BookMixinGenericAPIView.as_view()), url(r‘^v3/books/(?P<pk>.*)/$‘, views.BookMixinGenericAPIView.as_view()), ]
-
视图层
from rest_framework.mixins import ListModelMixin,RetrieveModelMixin,CreateModelMixin,UpdateModelMixin class BookMixinGenericAPIView(ListModelMixin, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin, GenericAPIView): # 继承GenericAPIView的目的: # 1.路由调用GenericAPIView父类APIView的as_view()方法 # 2.调用APIView的dispatch完成方发 # 3.需要GenericAPIView类提供的几个类属性和方法 queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer ? def get(self, request, *args, **kwargs): if ‘pk‘ in kwargs: # 单查:RetrieveModelMixin 中的retrieve()方法,内部是调用了GenericAPIView的get_object()方法 response = self.retrieve(request, *args, **kwargs) else: # 群查:ListModelMixin 中的list()方法,内部是调用了GenericAPIView的get_serializer(queryset, many=True)方法 response = self.list(request, *args, **kwargs) # mixins提供的方法响应的数据默认是Response # response.data即可拿到响应的数据 print(response.data) # {‘字段‘:‘字段值‘,...} return APIResponse(results=response.data) ? # 单增:CreateModelMixin 中的create()方法内部是调用了GenericAPIView的get_serializer(data=request.data)方法完成序列化,在保存 def post(self, request, *args, **kwargs): response = self.create(request, *args, **kwargs) return APIResponse(results=response.data) ? # 单 整体改: UpdateModelMixin 中的update()方法内部是调用了GenericAPIView的get_object()拿到具体对象,使partial=False到达整体改 def put(self, request, *args, **kwargs): response = self.update(request, *args, **kwargs) return APIResponse(results=response.data) # 单 局部改: UpdateModelMixin 中的update()方法内部是调用了GenericAPIView的get_object()拿到具体对象,使partial=True到达局部改 def patch(self, request, *args, **kwargs): response = self.partial_update(request, *args, **kwargs) return APIResponse(results=response.data)
三.generics 工具视图
1)工具视图都是GenericAPIView的子类,且不同的子类继承了不同的工具类,重写了请求方法 - ListCreateAPIView: 群查,单增 内部封装了list(), create()方法 - UpdateAPIView: 单局部改(单删),单整体改 内部封装了update(), partial_update方法 2)工具视图的功能如果直接可以满足需求,只需要继承工具视图,提供queryset与serializer_class即可
-
路由层
urlpatterns = [ url(r‘^v4/books/$‘, views.BookListCreatePIView.as_view()), url(r‘^v4/books/(?P<pk>.*)/$‘, views.BookListCreatePIView.as_view()), ]
-
视图层
from rest_framework.generics import ListCreateAPIView, UpdateAPIView class BookListCreatePIView(ListCreateAPIView, UpdateAPIView): queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer
四.viewsets 视图集
1)视图集都是优先继承ViewSetMixin类,再继承一个视图类(GenericAPIView或APIView) # GenericViewSet、ViewSet 2)ViewSetMixin提供了重写的as_view()方法,继承视图集的视图类,配置路由时调用as_view()必须传入 {请求名:函数名} 映射关系字典 # eg: url(r‘^v5/books/$‘, views.BookGenericViewSet.as_view({‘get‘: ‘my_get_list‘})), # 表示get请求会交给my_get_list视图函数处理
-
路由层
urlpatterns = [ # View的as_view():将get请求映射到视图类的get方法 # ViewSet的as_view({‘get‘: ‘my_get_list‘}):将get请求映射到视图类的my_get_list方法 url(r‘^v5/books/$‘, views.BookGenericViewSet.as_view({‘get‘: ‘my_get_list‘})), url(r‘^v5/books/(?P<pk>.*)/$‘, views.BookGenericViewSet.as_view({‘get‘: ‘my_get_obj‘})), ]
-
视图层
from rest_framework.viewsets import GenericViewSet from rest_framework import mixins class BookGenericViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer # 群查 def my_get_list(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) # 单查 def my_get_obj(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs)
GenericAPIView 与 APIView 区别
# GenericAPIView 与 APIView 最为两大继承视图的区别 # 1)GenericViewSet和ViewSet都继承了ViewSetMixin,as_view都可以配置 {请求:函数} 映射关系 # 2)GenericViewSet继承的是GenericAPIView视图类,用来完成标准的 model 类操作接口 # 3)ViewSet继承的是APIView视图类,用来完成不需要 model 类参与,或是非标准的 model 类操作接口 # post请求在标准的 model 类操作下就是新增接口,登陆的post不满足 # post请求验证码的接口,不需要 model 类的参与 # 案例:登陆的post请求,并不是完成数据的新增,只是用post提交数据,得到的结果也不是登陆的用户信息,而是登陆的认证信息
?
五.工具视图集 ModelViewSet
-
视图层
# 拥有六大接口:单查、群查、单增、单删、单整体改、单局部改 # 注:一般肯定会重写destroy from rest_framework.viewsets import ModelViewSet class BookModelViewSet(ModelViewSet): queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer ? # 单删 改字段 def destroy(self, request, *args, **kwargs): instance = self.get_object() # 拿到具体的model类 if not instance: return APIResponse(1, ‘删除失败‘) # 改字段 instance.is_delete = True instance.save() return APIResponse(0, ‘删除成功‘) # 查 def get(self, request, *args, **kwargs): response = self.list(request, *args, **kwargs) return APIResponse(results=response.data) # ...
-
路由层
urlpatterns = [ url(r‘^v6/books/$‘, views.BookModelViewSet.as_view({‘get‘: ‘list‘, ‘post‘: ‘create‘})), url(r‘^v6/books/(?P<pk>.*)/$‘, views.BookModelViewSet.as_view({‘get‘: ‘retrieve‘, ‘put‘: ‘update‘, ‘patch‘: ‘partial_update‘, ‘delete‘: ‘destroy‘})), ]
路由组件
from django.conf.urls import include from rest_framework.routers import SimpleRouter router = SimpleRouter() # 所有路由与ViewSet视图类的都可以注册,会产生 ‘^v6/books/$‘ 和 ‘^v6/books/(?P<pk>[^/.]+)/$‘ router.register(‘v6/books‘, views.BookModelViewSet) ? urlpatterns = [ # 第一种添加子列表方式 url(r‘^‘, include(router.urls)), ] # 第二种添加子列表方式 # urlpatterns.extend(router.urls)
drf框架 - 视图家族 | GenericAPIView | mixins | generics | viewsets