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)