看一下优化以前的代码
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的类结构图
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