视图基类、扩展类、子类及试图集等相关内容-85

1 2个视图基类

# Django REST framwork 提供的视图的主要作用:
   控制序列化器的执行(检验、保存、转换数据)
   控制数据库查询的执行
# APIView:继承了原生Django的View
# GenericAPIView:继承了APIView
-queryset = models.Book.objects.all()
   -serializer_class = serializer.BookModelSerializer
   -get_queryset:获取配置的queryset
   -get_object:路由中的分组字段必须是pk
   -get_serializer:获取配置的序列化类
   
   
   
   
# 最终总结
#两个基类
APIView:如果跟models没有关系(没有数据库相关操作),就继承它
GenericAPIView:有关数据库操作,queryset 和serializer_class






 

2 5个视图扩展类

#5个视图扩展类(rest_framework.mixins)
CreateModelMixin:create方法创建一条
DestroyModelMixin:destory方法删除一条
ListModelMixin:list方法获取所有
RetrieveModelMixin:retrieve获取一条
UpdateModelMixin:update修改一条

 

3 9个子类视图

#9个子类视图(rest_framework.generics)
CreateAPIView:继承CreateModelMixin,GenericAPIView,有post方法,新增数据
DestroyAPIView:继承DestroyModelMixin,GenericAPIView,有delete方法,删除数据
ListAPIView:继承ListModelMixin,GenericAPIView,有get方法获取所有
UpdateAPIView:继承UpdateModelMixin,GenericAPIView,有put和patch方法,修改数据
RetrieveAPIView:继承RetrieveModelMixin,GenericAPIView,有get方法,获取一条


ListCreateAPIView:继承ListModelMixin,CreateModelMixin,GenericAPIView,有get获取所有,post方法新增
RetrieveDestroyAPIView:继承RetrieveModelMixin,DestroyModelMixin,GenericAPIView,有get方法获取一条,delete方法删除
RetrieveUpdateAPIView:继承RetrieveModelMixin,UpdateModelMixin,GenericAPIView,有get获取一条,put,patch修改
RetrieveUpdateDestroyAPIView:继承RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView,有get获取一条,put,patch修改,delete删除

 

4 视图集

#视图集

# ViewSetMixin:重写了as_view

# ViewSet:     继承ViewSetMixin和APIView
# GenericViewSet:继承ViewSetMixin, generics.GenericAPIView

# ModelViewSet:继承mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet
# ReadOnlyModelViewSet:继承mixins.RetrieveModelMixin,mixins.ListModelMixin,GenericViewSet

 

5 action的使用

# 只要继承了ViewSetMixin类
# 路由配置:path('books_mix/', views.BookView.as_view({'get':'lqz'}))
# 视图类的方法中就会有个action
class BookView(ViewSet):
   def lqz(self,request,*args,**kwargs):
       print(self.action)
       return Response('lqz')
   
   
# ViewSetMixin以后只要继承它,路由的配置就发生变化了,只需要写映射即可

 

 

6 路由的使用

# 自动生成路由
# SimpleRouter
# DefaultRouter

# 继承了ViewSetMixin的视图类,以后写路由,可以自动生成
from rest_framework import routers
# 实例化得到一个对象
router = routers.SimpleRouter()
# 注册进路由
router.register('books', views.BookSetView)
# 把自动生成的路由配置到urlpatterns中
-urlpatterns += router.urls
   -re_path(r'v1/', include(router.urls))
   
   
   
   
# 配置路由的方式
-最原始的
  -path('books/', views.BookAPIView.as_view()),
   -ViewSetMixin的视图类
  -path('books_set/', views.BookSetView.as_view({'get':'list','post':'create'}))
   -ViewSetMixin的视图类
  -自动生成,上面讲的
       
       
       
       
# action
-当自动生成路由的时候,由于视图类中还有其它方法,是无法自动生成路由的
   -加action装饰器:
  -methods:什么请求方式会触发被装饰函数的执行
       -detail:是True是基于带id的路由生成的,如果是False,是基于不带id的路由生成的
  -@action(methods=['get'], detail=True)

 

原文地址:https://www.cnblogs.com/usherwang/p/14266033.html