drf05-2个视图基类-5个扩展类-9个视图子类-视图集

1.2两个视图基类

#之前写了五个接口,继承APIView
#还可以继承GenericApiView:它帮了我们干很多事
#GeneriaAPIView.属性和方法
-属性
	-queryset     #要序列化的数据
	-serializer_class #序列化类
	--------了解--------------
	----lookup_field #通过get_object 获取单个对象的查询key值,value是路由中穿过来的
	--filter_backends #过滤类
	-pagination_class #分页类
	
-方法
	-get_queryset    #获取要序列化的数据
	-get_object      #根据lookup_field 配置参数获取单个对象
	-get_serializer   #获取序列化类,咱直接用的
	-get_serializer_class #获取序列化类,不是咱们直接用get_serializer调用了它

---了解-------
-filter_queryset    #跟过滤有关系
-paginate_xxx      #跟分页有关

1.1基于APIView写五个接口

class UserView(APIView):
	def  get(self,request):
	res_list =User.object.all()
	ser = UserSerializer(instance=res_list,many=True)
	return Response(ser.data)
def  post(self,request):
	ser = UserSerlizer(data =request.data)
	if ser.is_valid():
	    ser.save()
	    return Response({'code':100,'msg':"新增成功"},status=201)
	else:
	    return Response({'code':101,'msg':ser.error})
        
    class UserDetailView(APIView):
    	def get(self,request,pk):
    	         obj = User.objects.filter(pk=pk).first()
    	         ser = UserSerializer(instance=obj)
    	         return Response(ser.data)
    	def put(self,request,pk):
    		obj = User.objects.filter(pk=pk).first()
    		ser = UserSerializer(instance=obj,data=request.data)
    		if ser.is_valid(): 
    		ser.save()
    		return Response({'code':'101','msg':"修改成功"},status=201)
    	else:
    		return  Response({'code':101,'msg':ser.errors})	
            def delete(self,request,pk):
                  User.objects.filter(pk=pk).delete()
                  return Response('')

1.2 基于GenericAPIView写五个接口

class UserView(GenericAPIView):
#配置两关类属性
queryset =User.object.all()
serializer_class = UserSerializer
def get(self,request):
	res_list = self.get_queryset()
request Response(ser,data)

def post(self,request):
	ser = self.get_serilizer(data=request.data)
	if ser.is_valid()
    	  ser.save()
	      return Response({'code':100,'msg':'新增成功'},status=201)
	else:
	      return Response({'code':101,'msg':ser.errors})
 class UserDetailView(GenericAPIView):
 	queryset = User.objects.all()
 	serilizer_class = UserSerlizer
 	
 	def get(self,request,pk):
 		obj = self.get_object()
 		ser = self.get_serializer(instance=obj)
 		return Response(ser.data)
 		
 	def put(self,request,pk):
 		obj = self.get_object()
 		ser =self.get_serilizer(instance=obj,data=request.data)
 		if ser.is_valid():
 		    ser.save()
 		    return Response({'code':100,'msg':"修改成功"},status=201)
 		else:
 		    return Response({'code':101,'msg':ser.errors})
 		    
 	def delete(self,request,pk):
 		self.get_queryset().filter(pk=pk).delete()
 		reutn Response('')

5个视图扩展类

基于GenericAPIView+5个试图扩展类写接口、

必须配合GenericAPIView使用,不能配合APIView使用

from rest_framework.minins import RetrieveModelMin,CreateModelMixin,updateModeMinxin,DestoryModeMixin,ListModeMixin
class UserView(GenericAPIView,ListModelMinxin,CreateModelMinxin):
	queryset = User.objects.all()
	serializer_class = UserSerilizer
	
	def get(self,request,*args,**kwargs):
		return self.list(request,*args,**kwargs)
		
	def post(self,request,*args,**kwargs):
		return self.create(request,*args,**kwargs)
		
class  UserDetailView(GenericAPIView,RetrieveModelMixin,UpdateModelMinin,DestroyModelmixin)
	queryset =  User.object.all()
	serializer_class = UserSerializer
	
	def get(self,request,*args,**kwargs):
		return self.retrieve(request,*args,**kwargs)
		
	def put(self,request,*args,**kwargs):
		return self.retrieve(request,*args,**kwargs)	
	
	def delete(self,request,*args,**kwargs):
		return self.destroy(request,*arkgs,**kwargs)

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()
	
	serilizer_class = UserSerializer
	
class UserDetailView(RetrieveUpdateDestroyAPIView):
	queryset = User.objects.all()
	serializer_class = UserSerializer

视图集

继承ModelViewSet编写五个接口

#视图类
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
posted @ 2022-10-07 14:57  名字长的像一只老山羊  阅读(24)  评论(0编辑  收藏  举报