• view


    from rest_framework.viewsets import GenericViewSet
    from rest_framework.mixins import ListModelMixin
    from rest_framework.filters import SearchFilter
    from . import models, serializers
    
    # 搜索课程接口
    class SearchCourseViewSet(GenericViewSet, ListModelMixin):
        queryset = models.Course.objects.filter(is_delete=False, is_show=True).all()
        serializer_class = serializers.CourseSerializer
    
        pagination_class = pagination.PageNumberPagination
    
        filter_backends = [SearchFilter]
        search_fields = ['name']

    1 继承了GenericAPIview必须写

    queryset = models.Course.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = serializers.CourseSerializer

    包括了下列方法

    queryset = models.Book.objects.all()
    serializer_class = serializer.BookModelSerializer
    get_queryset:获取配置的queryset
    get_object:单条记录查询时使用,路由中的分组字段必须是pk
    get_serializer:获取配置的序列化类    

    2 GenericViewSet继承了ViewSetMixin,和GenericAPIView

    ViewSetMixin能自动生成路由

    3 这五个视图子类必须和GenericAPIview或继承它的类(GenericViewSet)写在一起

    from rest_framework.mixins import ...
    CreateModelMixin:create方法创建一条
    DestroyModelMixin:destory方法删除一条
    ListModelMixin:list方法获取所有
    RetrieveModelMixin:retrieve获取一条
    UpdateModelMixin:update修改一条

    因为这5个类中需要queryset和serializer_class作为参数和GenericAPIView的方法

    queryset = models.Course.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = serializers.CourseSerializer

    4 listmodelmixin源码

    class ListModelMixin:
        """
        List a queryset.
        """
        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)
  • 相关阅读:
    vim:去掉响铃
    vim:过一个字符
    Msys2:windows下好用的unix模拟器
    vim:折叠操作
    vim:inoremap命令
    vim:关于映射和跳出括号
    vim打造简易C语言编辑器(在用2016.7.10)
    vim利用插件管理工具-管理配置文件
    拨打电话的实现
    类似于抽奖活动的小程序
  • 原文地址:https://www.cnblogs.com/xupengjun/p/14254892.html
Copyright © 2020-2023  润新知