今日内容
- 1、 2 个视图基类
- 1.1基于APIView写5个接口
- 1.2 基于GenericAPIView写5个接口
- 2、5个视图扩展类
- 2.1 基于GenericAPIView+5个视图扩展类写接口
- 3、9个视图子类
- 3.1 基于9个视图子类写接口
- 4、 视图集
- 4.1 继承ModelViewSet编写5个接口
- 5、源码分析ViewSetMixin
- 6、总结
1. 2 个视图基类
# 之前写5个接口,继承APIView
# 还可以继承GenericAPIView:它帮我们干了好多事
# GenericAPIView:属性和方法
-属性
-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写5个接口
class UserView(APIView):
def get(self, request):
res_list = User.objects.all()
ser = UserSerializer(instance=res_list, many=True)
return Response(ser.data)
def post(self, request):
ser = UserSerializer(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(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': 100, '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写5个接口
class UserView(GenericAPIView):
# 配置两个 类属性
queryset = User.objects.all()
serializer_class = UserSerializer
# def get_queryset(self):
# if self.request.method=='GET':
# return User.objects.all()
# else:
# return Publish.object.all()
def get(self, request):
res_list = self.get_queryset() # 提高扩展性
ser = self.get_serializer(instance=res_list, many=True)
return Response(ser.data)
def post(self, request):
ser = self.get_serializer(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()
serializer_class = UserSerializer
def get(self, request, pk):
# obj = self.get_queryset().filter(pk=pk).first()
# queryset.get({'pk':'有名分组分出来的'}
obj = self.get_object() # 根据传入的pk,获取一条数据
ser = self.get_serializer(instance=obj)
return Response(ser.data)
def put(self, request, pk):
obj = self.get_object()
ser = self.get_serializer(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()
return Response('')
2 5个视图扩展类
2.1 基于GenericAPIView+5个视图扩展类写接口
### 必须配合GenericAPIView使用,不能配合APIView使用
from rest_framework.mixins import RetrieveModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin, \
ListModelMixin
# RetrieveModelMixin:写了一个Create方法,就是原来咱们post中的代码
# RetrieveModelMixin:retrieve,就是咱们原来的get
# UpdateModelMixin:update方法,就是咱们原来的put
# ListModelMixin:list方法,就是原来咱们的get
# DestroyModelMixin:destroy方法,就是原来咱们的delete
class UserView(GenericAPIView, ListModelMixin, CreateModelMixin):
# 配置两个 类属性
queryset = User.objects.all()
serializer_class = UserSerializer
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, UpdateModelMixin, DestroyModelMixin):
queryset = User.objects.all()
serializer_class = UserSerializer
def get(self,request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args,**kwargs):
return self.update(request,*args,**kwargs)
def delete(self, request, *args,**kwargs):
return self.destroy(request,*args,**kwargs)
3 9个视图子类
3.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
4 视图集
4.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'})),
5.源码分析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
6.总结
# 总结
-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