Django 之 drf 第三篇 视图类 路由的使用

------------恢复内容开始------------

Django 之 drf 第三篇   视图类   路由的使用

一、两个视图基类

#Django REST  framwork  提供的视图的主要作用
    控制序列化器的执行(检验、保存、转换数据)
    控制数据库查询的执行
#APIView:继承了原生Djiango的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)
CerateModelMixin:create方法创建一条
DestroyModelMixin:destory  方法删除一条
ListModelMixin:list方法获取所有
RetrieveModelMixin:retrieve获取一条
UpdateModelMixin:update修改一条

 3、9个子类视图

#9个子类视图(rest_framework.f)

CreateAPIView:继承了CreateModelMixin,GenericAPIView,有post方法,新增数据
DestoryAPIView:继承了DestoryModelMixin,GenericAPIView,有delete方法,删除数据
ListAPIView:继承了ListModelMixin,GenericAPIView,有get方法获取所有数据
UpdateAPIView:继承了UpdateModelMixin,GenericAPIView,有put,patch方法,修改数据
RetrieveAPIView:继承了RetrieveModelMixin,GenericAPIView,有get方法,获取一条数据



ListCreateAPIView:继承了ListModelMixin,CreateModelMixin,GenericAPIView,有post,get方法,可以查看所有数据和增加数据
RetrieveUpdateMixin: 继承了RetrieveModelMixin,UpdateModelMixin,GenericAPIView,有put,patch,get方法,可以查看一条数据,修改数据
RetrieveDestroyAPIView:继承RetrieveModelMixin,DestroyModelMixin,GenericAPIView,有get方法获取一条,delete方法删除
RetrieveUpdateDestroyAPIView:继承RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView,有get获取一条,put,patch修改,delete删除

4 视图集

#视图集
ViewSetMixin:重写了as_cview

ViewSet:  继承了ViewSetMixin和APIView

GenericViewSet:  继承了ViewSetMixin,generic.GenericAPIView

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

5 action的使用

#只要继承了ViewSetMixin类
#路由配置:path('book_mix/',views.BookView.as_view({'get':'lqz'}))
#视图类的方法中就会有个action
class BookView(Viewset):
        def lqz(self,request,*args,**kwargs):
                print(self,action)
                return  Response('lqz')


#ViewSetMixin以后只要继承它,路由的配置就发生变化了,只需要写映射即可

 7 路由的使用

#自动生成路由
#SimpleRouter
#DefaultRouter


#继承了ViewSetMixin的视图类,以后写路由,可以自动生成
from rest_framework import routers
#实例化得到一个对象
router = routers.SimpleRouter()
#注册进路由
router.register('books',view.BookSetView)
#把自动生成的路由配置到urlpatterns中
    -urlpatterns += router.urls
    
    -re_path(r'v1/',include(router.uels))

#配置路由的方式
    
       -最原始的
             -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/ltyc/p/13939310.html