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的子类,且不同的子类继承了不同的工具类,重写了请求方法 -- UpdateAPIView: 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提交数据,得到的结果也不是登陆的用户信息,而是登陆的认证信息
''' 继承关系: APIView(View) GenericAPIView(APIView) GenericVieaSet( ViewSetMixin, generics.GenericAPIView) ModelViewSet( mixins.CreateModelMixin,增 mixins.RetreveModelMixin,单查 mixins.UpdateModelMixin,单/整改 mixins.DestroyModelMixin,删 mixins.ListModelMixin,群查 GenericViewSet,路由{}映射 ) CreateAPIView( mixins.CreateModelMixin, GenericAPIView ) ListAPIView( mixins.ListModelMixin, GenericAPIView ) RetrieveAPIView( mixins.RetrieveModelMixin, GenericAPIView ) DestroyAPIView( mixins.DestroyModelMixin, GenericAPIView ) UpdateAPIView( mixins.UpdateModelMixin, GenericAPIView ) ListCreateAPIView( mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView ) RetrieveUpdateAPIView( mixins.RetrieveModelMixin, mixins.UpdateModelMixin, GenericAPIView ) RetrieveDestroyAPIView( mixins.RetrieveModelMixin, mixins.DestroyModelMixin, GenericAPIView ) RetrieveUpdateDestroyAPIView( mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, GenericAPIView ) '''
五.工具视图集 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, '删除成功')
-
路由层
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'})), ]
总结:
""" 视图家族 1、视图类:APIView、GenericAPIView APIView:作为drf的基础view;as_view()禁用csrf;dispatch()二次封装request、三大认证、解析、渲染、响应、异常等模块;一堆类属性,可以用来做全局或局部插拔配置 GenericAPIView:继承APIView;三个方法三个属性(obj,queryset,serializer) 2、视图工具集:mixin五大工具类(六个方法) mixin.ListModelMixin - list:群查 mixin.RetreveModelMixin - retrieve:单查 mixin.CreateModelMixin - create:单增 mixin.DestroyModelMixin - destroy:单删 mixin.UpdateModelMixin - update:单整体改 mixin.UpdateModelMixin - partial_update:单局部改 前提:工具类都是由GenericAPIView的子类来继承 3、视图工具:generic各种子类(共10个子类) ListAPIView(ListModelMixin, GenericAPIView):继承该类的视图类,只需要提供几个类属性,就可以完成群查,不需要书写get方法 ListCreateAPIView(ListModelMixin, CreateModelMixin, GenericAPIView) 4、视图集:ViewSet、GenericViewSet ViewSetMixin:重写as_view(),可以将请求方法与视图类中的自定义函数名完成映射 as_view({'get': 'list', 'post': 'my_post'}) GenericViewSet:可以自定义请求映射的Model操作视图集 ViewSet:可以自定义请求映射的任意操作视图集(一般与Model操作不是那么密切相关) 登陆的post并非新增、短信的验证码(get或post)都和model无关 """
名称 | 父类 | 请求方法 | 功能 | 特点 | |
APIView | View | post, get, put, patch, delete | 增删改查 | 重写as_view()方法,二次封装request,三大认证,dispatch分发 | |
generics.py | GenericAPIView | APIView | post, get, put, patch, delete | 增删改查 | 提供了三个方法三个属性(obj,queryset,serializer) |
viewsets.py | ViewSetMixin | post, get, put, patch, delete | 增删改查 | 重写as_view()方法,请求方法与函数映射 | |
ViewSet | ViewSetMixin, APIView | post, get, put, patch, delete | 增删改查 | 提供映射 , dispatch分发 | |
GenericViewSet | ViewSetMixin, GenericAPIView | post, get, put, patch, delete | 增删改查 | 提供映射, dispatch分发, 三个属性与方法 | |
ModelViewSet | mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet |
post, get, put, patch, delete | 增删改查 | ||
mixins.py | CreateModelMixin | 增 | 提供create()方法, 内部用到get_serializer反序列化,所以需要其子类继承GenericAPIView | ||
ListModelMixin | 群查 | 提供list()方法, 内部用到get_serializer序列化,所以需要其子类继承GenericAPIView | |||
RetrieveModelMixin | 单查 | 提供retrieve()方法, 内部用到get_serializer,get_object,所以需要其子类继承GenericAPIView | |||
UpdateModelMixin | 单 局/整 改 | 提供update()方法, 内部用到get_serializer,get_object,所以需要其子类继承GenericAPIView | |||
generics.py | CreateAPIView | mixins.CreateModelMixin, GenericAPIView | post | 增 | 提供create()方法,dispatch分发, 三个属性与方法 |
ListAPIView | mixins.ListModelMixin, GenericAPIView | get | 群查 | 提供list()方法,dispatch分发, 三个属性与方法 | |
RetrieveAPIView | mixins.RetrieveModelMixin, GenericAPIView | get | 单查 | 提供retrieve()方法,dispatch分发, 三个属性与方法 | |
UpdateAPIView | mixins.UpdateModelMixin, GenericAPIView | put/patch | 单 局/整 改 | 提供update(), partial_update()方法,dispatch分发, 三个属性与方法 | |
ListCreateAPIView | mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView | get/post | 群查/单增 | 提供list(),create()方法,dispatch分发, 三个属性与方法 |
路由组件 routers
from django.conf.urls import include from rest_framework.routers import SimpleRouter router = SimpleRouter() # SimpleRouter类内部做了{请求:函数}的映射关系 # 所有路由与ViewSet视图类的都可以注册,会产生 '^v6/books/$' 和 '^v6/books/(?P<pk>[^/.]+)/$' router.register('v6/books', views.BookModelViewSet) urlpatterns = [ # 第一种添加子列表方式 url(r'^', include(router.urls)), ] # 第二种添加子列表方式 # urlpatterns.extend(router.urls)
SimpleRouter 源码:
class SimpleRouter(BaseRouter): # 没有 pk 时做的映射关系 routes = [ # List route. Route( url=r'^{prefix}{trailing_slash}$', # 没有pk # 映射关系 mapping={ 'get': 'list', 'post': 'create' }, name='{basename}-list', detail=False, initkwargs={'suffix': 'List'} ), # 有 pk 时做的映射关系 Route( url=r'^{prefix}/{lookup}{trailing_slash}$', # 有pk # 映射关系 mapping={ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }, name='{basename}-detail', detail=True, initkwargs={'suffix': 'Instance'} ),