视图家族
Posted setcreed
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了视图家族相关的知识,希望对你有一定的参考价值。
目录
视图家族简介
from rest_framework import views, mixins, generics, viewsets
views
:视图类APIView,GenericAPIView(generics中)
mixins
:视图工具类CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
generics
:工具视图类 有九个类viewsets
:视图集 两个视图集基类,两个视图集子类,一个工具类
视图类APIView
- 继承View,拥有View的所有
- 重写了as_view方法,局部禁用csrf认证
- 重写dispatch
- 增加一系列类属性,局部 渲染和解析配置
视图类GenericAPIView
GenericAPIView 继承APIView,拥有APIView的所有方法、属性
# 工具视图类
from rest_framework.generics import GenericAPIView
class CarGenericAPIView(GenericAPIView):
# 不能直接写到objects结束,因为objects结束时,不是QuerySet对象,而是Manager对象,但 .all() 和 .filter() 后一定是QuerySet对象
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializer.CarModelSerializer
lookup_url_kwarg = 'pk'
# 群查
"""
def get(self, request, *args, **kwargs):
car_query = self.get_queryset()
car_ser = self.get_serializer(car_query, many=True)
return APIResponse(results=car_ser.data)
"""
# 单查
def get(self, request, *args, **kwargs):
car_obj = self.get_object()
car_ser = self.get_serializer(car_obj)
return APIResponse(results=car_ser.data)
GenericAPIView总结:
- 继承APIView,拥有APIView的所有
get_queryset
方法,配置queryset
类属性,提供视图类相关的Models- 在
get_queryset
方法的基础上,有了get_object
方法,配置lookup_url_kwarg
属性,提供视图类相关的具体的models get_serializer
方法,配置serializer_class
类属性,提供视图类相关的序列化对象
GenericAPIView就是在APIView的基础上额外提供了三个方法、三个类属性,如果不配合视图工具类,体现不出优势
其目的:视图中的增删改查逻辑相似,但操作的资源不一致,操作资源就是操作 资源对象们、资源对象以及资源相关的序列化类,将这三者形成配置,那操作逻辑就一致,就可以进行封装。
视图工具类mixins
# mixins视图工具类
from rest_framework.mixins import RetrieveModelMixin, ListModelMixin, CreateModelMixin
class CarReadCreateGenericAPIView(RetrieveModelMixin, ListModelMixin, CreateModelMixin, GenericAPIView):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializer.CarModelSerializer
lookup_url_kwarg = 'pk'
# 群查
"""
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
"""
# 单查
def get(self, request, *args, **kwargs):
response = self.retrieve(request, *args, **kwargs)
return APIResponse(results=response.data)
# 单增
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
- mixins视图工具类:有五个类、六个方法
- 需要配合
GenericAPIView
类使用,将单查、群查、单增、整体单改、局部单改、单删六个接口封装成retrieve
、list
、create
、update
、partial_update
、destroy
六个方法 - 调用的方法就是
GenericAPIView
提供的,配合GenericAPIView
类使用
工具视图类generics
# 单独完成单查接口
from rest_framework.generics import RetrieveAPIView
class CarRetrieveAPIView(RetrieveAPIView):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializer.CarModelSerializer
lookup_url_kwarg = 'pk'
# 单独完成群查接口
from rest_framework.generics import ListAPIView
class CarListAPIView(ListAPIView):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializer.CarModelSerializer
# 完成单查接口、整体单改接口、局部单改接口、单删接口
from rest_framework.generics import RetrieveUpdateDestroyAPIView
class CarRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializer.CarModelSerializer
generics
工具视图类 有九种组合
- 帮我们将不同种类的
mixins
与GenericAPIView
进行组合 - 不同的组合帮我们实现好对应的
get
、post
、put
、patch
、delete
方法 - 只要我们自己配置三个类属性即可:
queryset
、serializer_class
、lookup_url_kwarg
视图集viewsets
这里的ViewSetMixin
重写了as_view
方法
# 视图集
from rest_framework.viewsets import ViewSetMixin, ViewSet, GenericViewSet, ModelViewSet
class CarReadOnlyAPIView(RetrieveModelMixin, ListModelMixin, GenericViewSet):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializer.CarModelSerializer
# urls.py
url(r'^v7/cars/$', views.CarReadOnlyAPIView.as_view({'get': 'list'})),
url(r'^v7/cars/(?P<pk>d+)/$', views.CarReadOnlyAPIView.as_view({'get': 'retrieve'})),
视图集实现六大接口
# 实现了六大接口,单查、群查、单增、整体单改、局部单改、单删
class CarModelViewSet(ModelViewSet):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializer.CarModelSerializer
# urls.py
url(r'^v8/cars/$', views.CarModelViewSet.as_view({
'get': 'list',
'post': 'create'
})),
url(r'^v8/cars/(?P<pk>d+)/$', views.CarModelViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
}))
这样设计的不合理点:
- 没有群增、整体群改、局部群改、群删 四个接口
- 删除操作视图集默认 走的是
destroy
方法, 是将资源从数据库中删除,而不是将一个字段is_delete
字段修改 - 响应的结果只有数据,没有数据状态码和状态信息
解决视图集的不合理
# 实现了六大接口,单查、群查、单增、整体单改、局部单改、单删
class CarModelViewSet(ModelViewSet):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializer.CarModelSerializer
# 群整体改,群局部改,全删三个接口可以独立成三个方法
def many_update(self, request, *args, **kwargs):
request_data = request.data
try:
pks = []
for dic in request_data:
pk = dic.pop('pk')
pks.append(pk)
car_query = models.Car.objects.filter(is_delete=False, pk__in=pks).all()
if len(pks) != len(car_query):
raise Exception('pk对应的数据不存在')
except Exception as e:
return Response({'detail': '%s' % e}, status=400)
car_ser = serializer.CarModelSerializer(instance=car_query, data=request_data, many=True)
car_ser.is_valid(raise_exception=True)
car_list = car_ser.save()
return APIResponse(results=serializer.CarModelSerializer(instance=car_list, many=True).data)
def many_partial_update(self, request, *args, **kwargs):
request_data = request.data
try:
pks = []
for dic in request_data:
pk = dic.pop('pk')
pks.append(pk)
car_query = models.Car.objects.filter(is_delete=False, pk__in=pks).all()
if len(pks) != len(car_query):
raise Exception('pk对应的数据不存在')
except Exception as e:
return Response({'detail': '%s' % e}, status=400)
car_ser = serializer.CarModelSerializer(instance=car_query, data=request_data, partial=True, many=True)
car_ser.is_valid(raise_exception=True)
car_list = car_ser.save()
return APIResponse(results=serializer.CarModelSerializer(instance=car_list, many=True).data)
def many_destroy(self, request, *args, **kwargs):
pks = request.data
try:
rows = models.Car.objects.filter(is_delete=False, pk__in=pks).update(is_delete=True)
except:
return APIResponse(1, '数据有误')
if rows:
return APIResponse(0, '删除成功')
return APIResponse(1, '删除失败')
# 群增与单增必须公用一个接口,都要走create方法 - 重写create方法,用逻辑进行拆分
def create(self, request, *args, **kwargs):
if isinstance(request.data, list):
car_ser = serializer.CarModelSerializer(data=request.data, many=True)
car_ser.is_valid(raise_exception=True)
car_obj = car_ser.save()
return APIResponse(results=serializer.CarModelSerializer(car_obj, many=True).data)
return super().create(request, *args, **kwargs)
# destroy方法是完成is_delete字段值修改 - 重写destroy方法,自定义实现体
def destroy(self, request, *args, **kwargs):
car_obj = self.get_object()
car_obj.is_delete = True
car_obj.save()
return APIResponse(msg='删除成功')
# 让群查有状态码和状态信息 - 重写list方法
def list(self, request, *args, **kwargs):
response = super().list(request, *args, **kwargs)
return APIResponse(results=response.data)
# 重写retrieve方法
def retrieve(self, request, *args, **kwargs):
response = super().retrieve(request, *args, **kwargs)
return APIResponse(results=response.data)
# urls.py
url(r'^v8/cars/$', views.CarModelViewSet.as_view({
'get': 'list',
'post': 'create',
'put': 'many_update',
'patch': 'many_partial_update',
'delete': 'many_destroy'
})),
url(r'^v8/cars/(?P<pk>d+)/$', views.CarModelViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
}))
视图集总结:
- 核心:视图集都继承了
ViewSetMixin
类,该类重写了as_view
方法,相比APIView的as_view
方法,额外多出了一个参数actions
,as_view({‘get‘: ‘list‘})
传入的{‘get‘: ‘list‘}
就被actions参数
接收,原理是将get请求映射到视图类的list 函数进行处理 - 在源码中
GenericViewSet
和ViewSet
两个视图集基类GenericViewSet(ViewSetMixin, GenericAPIView)
,该分支严格满足资源接口ViewSet(ViewSetMixin, views.APIView)
, 该分支吗,满足的接口与资源Model类关系 不是特别密切:如登录接口、短信验证码接口
ReadOnlyModelViewSet
与ModelViewSet
两个视图集子类,就是做一堆mixins与GenericViewSet
的组合,自己在urls.py
文件中配置as_view
设置映射关系。
补充路由层写法
# urls.py
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('v8/cars', views.CarModelViewSet, basename='car')
url(r'', include(router.urls))
以上是关于视图家族的主要内容,如果未能解决你的问题,请参考以下文章