Django之from rest_framework import viewsets

'''
我们不是编写多个视图,而是将所有常见的行为组合到一个名为viewset的类中。

如果需要的话,我们可以很容易地将它们分解为单独的视图,但是使用viewset使视图逻辑组织得很好,并且非常简洁。
'''

class UserViewSet(viewsets.ModelViewSet):
	pass

源码:

# 这个类就比较适合做后台功能的父类,包含需要的基本操作,同时可以非常方便的控制权限
class ModelViewSet(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet):
    """
    A viewset that provides default `create()`, `retrieve()`, `update()`,
    `partial_update()`, `destroy()` and `list()` actions.
    """
    pass
from rest_framework import viewsets, filters
from rest_framework.response import Response
from rest_framework.decorators import (authentication_classes, detail_route, list_route)


from restapp.serializers import UserInformationSerializer
from restapp.models import UserInformation


from utils.restpage import StandardResultsSetPagination, LargeResultsSetPagination


# 测试viewsets.ModelViewSet的各项功能
class Test_ModelViewSet(viewsets.ModelViewSet):
    queryset = UserInformation.objects.filter()
    serializer_class = UserInformationSerializer
    # 过滤器
    filter_backends = [filters.DjangoFilterBackend]

    # 定义需要使用过滤器的字段
    filter_fields = ("age",'passwd','usetype_id','owner_id')
    # 权限列表
    permission_classes = []
    # pagination_class = StandardResultsSetPagination
    # 分页设置
    pagination_class = LargeResultsSetPagination

    def list(self, request, *args, **kwargs):
        '''
        请求:http://127.0.0.1:8000/restapps/testviewsets/ 得到如下结果
        '{"count":4,
        "next":"http://127.0.0.1:8000/restapps/testviewsets/?page=2",
        "previous":null,
        "results":[
            {"id":1,"name":"admin大哥","age":30,"passwd":"123456"},
            {"id":2,"name":"shixf大哥","age":30,"passwd":"123456"},
            {"id":3,"name":"阿龙大哥","age":30,"passwd":"123456"},
            {"id":4,"name":"阿迪大哥","age":30,"passwd":"123456"}
        ]}'
        '''

        # Note the use of `get_queryset()` instead of `self.queryset`
        queryset = self.filter_queryset(self.get_queryset())
        serializer = UserInformationSerializer(queryset, many=True)
        page = self.paginate_queryset(queryset)
        data_list = serializer.data
        if page is not None:
            data_list = serializer.data
            # 为给定的输出数据返回分页样式的Response对象
            return self.get_paginated_response(data_list)
        return Response(serializer.data)

	# 确认是详情的路由,还是列表路由
    @detail_route(methods=["GET"])
    def get_questionnaires(self,request):
        return Response({'code':200})

属性:
queryset 设置结果集
serializer_class 设置序列化器
lookup_field 查询指定的对象

方法:
get_queryset(self) 返回视图使用的查询集
get_serializer(self,_args, *_kwargs) 返回序列化器对象
get_object(self) 返回详情视图所需的模型类数据对象

你可能感兴趣的:(django,django)