DRF之视图家族
一:
# 路由层 urlpatterns = [ url(r'^v2/books/$', views.BookGenericAPIView.as_view()), url(r'^v2/books/(?P<pk>.*)/$', views.BookGenericAPIView.as_view()), ]
# 视图层
def get(self, request, *args, **kwargs): # 传统的群查方式 单查同样 此处不列举 book_query = models.Book.objects.all().filter(is_delete=False) book_ser = serializers.BookModelSerializer(book_query, many=True) data = book_ser.data return APIResponse(results=data)
def get(self, request, *args, **kwargs):
# GenericAPIView 方式取值
book_query = self.get_queryset() # 获取序列化对象
book_ser = self.get_serializer(book_query,many=True) # 进行序列化
book_data = book_ser.data # 获取数据
return APIResponse(results=book_data)
PS:
(1)此种方式会报错 没有获取queryset对象
(2)没有获取序列化类
queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer def get(self, request, *args, **kwargs): # GenericAPIView 方式取值 book_query = self.get_queryset() # 获取序列化对象 book_ser = self.get_serializer(book_query,many=True) # 进行序列化 book_data = book_ser.data # 获取数据 return APIResponse(results=book_data)
PS:
(1)get_queryset():从类属性queryset中获得model的queryset数据
(2)get_object():从类属性queryset中获得model的queryset数据,再通过有名分组pk确定唯一操作对象
(3)get_serializer():从类属性serializer_class中获得serializer的序列化类
# 单取 lookup_field = 'pk' # 可以通过该方法自定义主键名称 def get(self, request, *args, **kwargs): book_query = self.get_object() book_ser = self.get_serializer(book_query) book_data = book_ser.data return APIResponse(results=book_data)
PS:
(1)上述代码结构看起来感觉代码量不减少反而增加
(2)别急 请看下面的
二:mixins视图工具集
(1)作用:
(1)提供了五个工具类
(2)提供了六个工具方法,单查,群查,单增,单删,单整体改,单局部改
(2)特点
(1)mixins需要继承
(2)调用GenericAPIView 中的queryset ,serializer_class 以及函数中的一些方法get方法
(3)代码示例
# 路由层 url(r'^v3/books/$', views.BookMixinAPIView.as_view()), url(r'^v3/books/(?P<pk>.*)/$', views.BookMixinAPIView.as_view()),
# 视图层 # 导入方法模块 from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin,UpdateModelMixin
class BookMixinAPIView(ListModelMixin, GenericAPIView, RetrieveModelMixin, CreateModelMixin,UpdateModelMixin): queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer # 群查 单查 def get(self, request, *args, **kwargs): print(self) # <api.views.BookMixinAPIView object at 0x0000000005456A20> 当前视图类 if 'pk' in kwargs: # 判断主键 是否在kwargs中 # 单查 response = self.retrieve(request, *args, **kwargs) else: # 群查 response = self.list(request, args, **kwargs) # 数据的返回值都是在data中 通过.data获取数据 data = response.data # mixins提供的list方法返回值都是在response中 需要使用自己定义的APIResponse return APIResponse(results=data) # 添加数据 def post(self, request, *args, **kwargs): response = self.create(request, *args, **kwargs) data = response.data return APIResponse(results=data) # 单个整体改 def put(self, request, *args, **kwargs): response = self.update(request, *args, **kwargs) data = response.data return APIResponse(results=data) # 单个局部改 def patch(self, request, *args, **kwargs): response = self.partial_update(request,*args,**kwargs) data = response.data
三:工具视图
(1)作用:
(1)工具视图都是GenericAPIView的子类 且不同子类继承不同的视图 提供了不同的方法
(2)工具视图的功能如果可以直接满足需求 只需要直接继承即可
(2)使用
# 路由层 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): # 群查 和单增 ListCreateAPIView queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer # UpdateAPIView 单局部修改 单整体修改
四:视图集
# 路由层 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.RetrieveModelMixin, mixins.ListModelMixin, 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)
PS:
(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视图函数处理
五:
# 1:GenericViewSet和ViewSet都继承了ViewSetMixin,as_view都可以配置 请求-函数 映射 # 2:GenericViewSet继承的是GenericAPIView视图类,用来完成标准的 model 类操作接口 # 3:ViewSet继承的是APIView视图类,用来完成不需要 model 类参与,或是非标准的 model 类操作接口 # post请求在标准的 model 类操作下就是新增接口,登陆的post不满足 # post请求验证码的接口,不需要 model 类的参与 # 案例:登陆的post请求,并不是完成数据的新增,只是用post提交数据,得到的结果也不是登陆的用户信息,而是登陆的认证信息
六:工具视图集
# 路由层 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 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() # type: models.Book if not instance: return APIResponse(1, '删除失败') # 实际操作,在此之前就做了判断 instance.is_delete = True instance.save() return APIResponse(0, '删除成功')
七:路由组件
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)