(19)Django Rest framwork-优化三(vie

2019-10-30  本文已影响0人  足__迹
# vieset类不在支持get,post,put,delete等方法,而只支持请求action动作
#但是vieset未提供get_serializer,filter_queryset,get_object()
#所以继承了GenericViewSet
class projectViewset(viewsets.GenericViewSet):
    # 指定查询集合(所有的查询数据)
    queryset = Projects.objects.all()
    # 指定序列化器
    serializer_class = ProjectModelSerializer
    # 在视图类中指定过滤引擎(可以指定多个过滤器) OrderingFilter排序过滤器  DjangoFilterBackend(筛选)
    filter_backends = [filters.OrderingFilter, DjangoFilterBackend]
    # 对特定字段进行排序,指定排序的字段
    ordering_fields = ['name', 'leader']
    # 对特定的筛选字段
    filterset_fields = ['name', 'leader']

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


设置路径映射

    path('projectset/', views.projectViewset.as_view({

        'get': 'list',
        'post': 'create',
    })),
    path('projectset/<int:pk>/', views.projectViewset.as_view({

        'get': 'retrieve',
        'put': 'update',
        'delete': 'destroy',
    }))

当前优化第一步已经实现了根据活动判断操作,但是需要手动编辑操作还是麻烦,我们引入mixins,
但是我们的操作复杂,继承的方法多,django提供了ModelViewSet


image.png

第一步优化后:

class projectViewset(viewsets.ModelViewSet):
    # 指定查询集合(所有的查询数据)
    queryset = Projects.objects.all()
    # 指定序列化器
    serializer_class = ProjectModelSerializer
    # 在视图类中指定过滤引擎(可以指定多个过滤器) OrderingFilter排序过滤器  DjangoFilterBackend(筛选)
    filter_backends = [filters.OrderingFilter, DjangoFilterBackend]
    # 对特定字段进行排序,指定排序的字段
    ordering_fields = ['name', 'leader']
    # 对特定的筛选字段
    filterset_fields = ['name', 'leader']
 @action(methods=['get'], detail=False)
    def names(self, request, *args, **kwargs):
        # 方法一 返回项目名列表
        # queryset = self.filter_queryset(self.get_queryset())
        # serializer = self.get_serializer(queryset, many=True)
        # list = []
        #
        # for i in serializer.data:
        #     list.append(i['name'])
        # return Response(list)
        #
        # 方法二 使用校验器
        queryset = self.get_queryset()
        #使用自定义的序列化器实现
        serializer = ProjectNameSerializer(instance=queryset,many=True)
        return Response(serializer.data)


    #获取项目下的接口
    @action(detail=False)
    def interface(self,request, *args,**kwargs):
       
        instance = self.get_object()
        serializer = InterfaceByIDSerializer(instance=instance)
        return Response(serializer.data)

设置url

  path('projectset/names/',views.projectViewset.as_view({
        'get': 'names',
    }),name = 'project_name'),
    path('projectset/<int:pk>/interface/', views.projectViewset.as_view({
        'get': 'interface',
    }), name='project_interface'),
#创建路由对象
router = routers.SimpleRouter()
#注册路由
#第一个参数prefix为路由前缀,一般添加应用名
#第二个参数为viewset视图集,不要添加.as_view()
router.register('project',views.projectViewset)
urlpatterns  += router.urls
上一篇下一篇

猜你喜欢

热点阅读