1. 9个视图子类
1.1 基于9个视图子类写接口
视图类:继承GenericAPIView+某个或某几个视图扩展类
from rest_framework.generics import ListAPIView,CreateAPIView, RetrieveAPIView,DestroyAPIView,UpdateAPIView
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView,RetrieveUpdateAPIView,RetrieveDestroyAPIView
# 正常来讲 Destroy+Update 应该有一个 ,作者没加
class UserView(ListCreateAPIView):
# 配置两个 类属性
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetailView(RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
2 视图集
1.1 继承ModelViewSet编写5个接口
视图类
from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet
class UserView(ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
路由
path(‘user/’, views.UserView.as_view({‘get’: ‘list’, ‘post’: ‘create’})),
path(‘user/int:pk’, views.UserView.as_view({‘get’: ‘retrieve’, ‘put’: ‘update’, ‘delete’: ‘destroy’})),
源码分析ViewSetMixin
@classonlymethod
def as_view(cls, actions=None, **initkwargs):
# 路由中as_view中必须传参数,必须传字典:{'get': 'list', 'post': 'create'}
if not actions:
raise TypeError("The `actions` argument must be provided when "
"calling `.as_view()` on a ViewSet. For example "
"`.as_view({'get': 'list'})`")
# 路由匹配成功,执行view(request),request是老的request
def view(request, *args, **kwargs):
# actions={'get': 'list', 'post': 'create'}
for method, action in actions.items():
# method:get action:list
# self 是视图类的对象中通过反射,查找list,
# handler视图类中的list方法
handler = getattr(self, action)
# 向视图类的对象中,反射 method:get,handler:list方法
# self.get=list
setattr(self, method, handler)
return self.dispatch(request, *args, **kwargs)
return csrf_exempt(view)
# 只要继承了ViewSetMixin,以后路由写法变量,都要协程:views.UserView.as_view({'get': 'list', 'post': 'create'}))
# 这样写好以后,对应的请求方式来了,就会执行配置的方法
扩展:
-以后只要继承了ViewSetMixin,视图类中可以写任意名字的方法,不用非得写get,post,delete
总结
-APIView:as_view,dispatch
-GenericAPIView:继承了APIView
-类属性
-方法
-5个视图扩展类:RetrieveModelMixin, CreateModelMixin, UpdateModelMixin,DestroyModelMixin, ListModelMixin
-每个类里面有一个方法
-9个视图子类:5个视图扩展类+GenericAPIView的组合
-视图集:
-ViewSetMixin:魔法,重写了as_view,只要继承他,路由写法就变了
-ViewSet:ViewSetMixin+APIView
-GenericViewSet:ViewSetMixin+GenericAPIView
-ModelViewSet:5个视图扩展类+GenericViewSet
ReadOnlyModelViewSet:2个视图扩展类+GenericViewSet