先来看看之前优化的代码:
from rest_framework.generics import GenericAPIView from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import OrderingFilter from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin from utils.pagination import NewPagination from .models import Projects from .serializers import ProjectsModelSerializer class ProjectsPage(ListModelMixin, CreateModelMixin, GenericAPIView): ''' 类视图 ''' queryset = Projects.objects.all() serializer_class = ProjectsModelSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_fields = ['id', 'name', 'leader', 'programmer', 'tester'] ordering_fields = ['id', 'name', 'leader', 'programmer', 'tester'] pagination_class = NewPagination 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 ProjectsDetailsPage(RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, GenericAPIView): queryset = Projects.objects.all() serializer_class = ProjectsModelSerializer def get(self, request, *args, **kwargs): self.retrieve(request, *args, **kwargs) def put(self, request, *args, **kwargs): self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs)
上面的代码优化只针对当前视图,一般一个项目会有很多个视图,如果有很多视图结构都跟上面的相似,那可不可以不要每次都cv这些请求方法呢?
本章我们通过generics模块中的一系列类来继续优化视图当中的请求方法,先看看generics模块的Structure:
generics模块下主要有以下类来做优化
- CreateAPIView:继承了mixins.CreateModelMixin和GenericAPIView
- ListAPIView:继承了mixins.ListModelMixin和GenericAPIView
- RetrieveAPIView:继承了mixins.RetrieveModelMixin和GenericAPIView
- DestroyAPIView:继承了mixins.DestroyModelMixin和GenericAPIView
- UpdateAPIView:继承了mixins.UpdateModelMixin和GenericAPIView
- ListCreateAPIView:继承了mixins.ListModelMixin、mixins.CreateModelMixin和GenericAPIView
- RetrieveUpdateAPIView:继承了mixins.RetrieveModelMixin、mixins.UpdateModelMixin和GenericAPIView
- RetrieveDestroyAPIView:继承了mixins.RetrieveModelMixin、mixins.DestroyModelMixin和GenericAPIView
- RetrieveUpdateDestroyAPIView:继承了mixins.RetrieveModelMixin、mixins.UpdateModelMixin、mixins.DestroyModelMixin和GenericAPIView
由于ProjectsPage视图类有获取项目列表信息的get请求和创建项目的post请求,因此可以继承ListCreateAPIView类来进行优化
class ProjectsPage(ListCreateAPIView): ''' 类视图 ''' queryset = Projects.objects.all() serializer_class = ProjectsModelSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_fields = ['id', 'name', 'leader', 'programmer', 'tester'] ordering_fields = ['id', 'name', 'leader', 'programmer', 'tester'] pagination_class = NewPagination
ProjectsDetailsPage视图类有获取项目详情的get请求,更新的put请求和删除项目的delete请求,因此可以继承RetrieveUpdateDestroyAPIView类来进行优化
class ProjectsDetailsPage(RetrieveUpdateDestroyAPIView): queryset = Projects.objects.all() serializer_class = ProjectsModelSerializer