获取全部信息
- 优化前:
def get(self, request):
project_qs = self.get_queryset()
'''
序列化器如果返回多条数据 需要添加:many=True
'''
project_qs = self.filter_queryset(project_qs) # 过滤查询集
page = self.paginate_queryset(project_qs) #使用paginate_queryset进行分页操作,返回分页之后的查询集
if page is not None:
serialier = self.get_serializer(instance=page, many=True)
#使用self.get_paginated_response 返回
return self.get_paginated_response(serialier.data)
serialier = self.get_serializer(instance=project_qs, many=True)
return Response(serialier.data)
-
使用优化的该函数mixins
对比 mixins中ListModelMixin中的list方法可以实现
image.png - 优化后:
def get(self, request,*args, **kwargs):
return self.list(request,*args,**kwargs)
综合优化后
class ProjectsView(mixins.ListModelMixin,mixins.CreateModelMixin,GenericAPIView):
# 指定查询集合(所有的查询数据)
queryset = Projects.objects.all()
# 指定序列化器
serializer_class = ProjectModelSerializer
# 在视图类中指定过滤引擎(可以指定多个过滤器) OrderingFilter排序过滤器 DjangoFilterBackend(筛选)
filter_backends = [filters.OrderingFilter,DjangoFilterBackend]
# 对特定字段进行排序,指定排序的字段
ordering_fields = ['name', 'leader']
#对特定的筛选字段
filterset_fields = ['name', 'leader']
def get(self, request,*args, **kwargs):
return self.list(request,*args,**kwargs)
def post(self, request,*args, **kwargs):
return self.create(request,*args, **kwargs)
# 需要继承GenericAPIView
class ProjrctView2(mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,GenericAPIView):
# 必须指定queryset和serializer_class
queryset = Projects.objects.all() # 用于指定需要使用的查询集
serializer_class = ProjectModelSerializer # 用于指定用到的序列化器类
filter_backends = [filters.OrderingFilter] #指定排序过滤引擎
#如果使用不是pk可以自定义lookup_field,可以修改
# lookup_field = 'id'
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)
网友评论