标签:额外 视图 必须 不一致 字段修改 try upd ref app
目录
from rest_framework import views, mixins, generics, viewsets
views
:视图类 APIView,GenericAPIView(generics中)
mixins
:视图工具类 CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
generics
:工具视图类 有九个类viewsets
:视图集 两个视图集基类,两个视图集子类,一个工具类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总结:
get_queryset
方法,配置queryset
类属性,提供视图类相关的Modelsget_queryset
方法的基础上,有了get_object
方法,配置lookup_url_kwarg
属性,提供视图类相关的具体的modelsget_serializer
方法,配置serializer_class
类属性,提供视图类相关的序列化对象GenericAPIView就是在APIView的基础上额外提供了三个方法、三个类属性,如果不配合视图工具类,体现不出优势
其目的:视图中的增删改查逻辑相似,但操作的资源不一致,操作资源就是操作 资源对象们、资源对象以及资源相关的序列化类,将这三者形成配置,那操作逻辑就一致,就可以进行封装。
# 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)
GenericAPIView
类使用,将单查、群查、单增、整体单改、局部单改、单删六个接口封装成retrieve
、list
、create
、update
、partial_update
、destroy
六个方法GenericAPIView
提供的,配合GenericAPIView
类使用# 单独完成单查接口
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
这里的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))
标签:额外 视图 必须 不一致 字段修改 try upd ref app
原文地址:https://www.cnblogs.com/setcreed/p/12122122.html