视图 :常用 1和4 两种 1. 原始的APIView class IndexView(views.APIView): def get(self, request, *args, **kwargs): user_list = models.UserInfo.objects.all() ser = IndexSerializer(instance=user_list,many=True) return Response(ser.data) 2. GenericAPIView(APIView) 里面实现了一些鸡肋的方法,没什么用 3. GenericViewSet(ViewSetMixin, generics.GenericAPIView) :在url中标注什么请求方法执行什么函数 路由修改: urlpatterns = [ url(r‘^index/$‘, views.IndexView.as_view({‘get‘:‘list‘,‘post‘:‘create‘})), url(r‘^index/(?P<pk>\d+)$‘, views.IndexView.as_view({‘get‘:‘retrieve‘,‘delete‘:‘remove‘})), ] 视图修改: class IndexView(viewsets.GenericViewSet): def list(self,request,*args,**kwargs): pass # 获取列表信息 def retrieve(self, request, *args, **kwargs): pass # 获取单条数据 def create(self,request, *args, **kwargs): pass 以前不用GenericViewSet的方式: 增 POST /users/ 删 DELETE /users/1/ 改 PUT 全部修改 /users/1/ patch 局部修改 /users/1/ 查 GET 全部数据 /users/ GET 一条数据 /users/1/ urlpatterns = [ url(r‘^index/$‘, views.IndexView.as_view()), url(r‘^index/(?P<pk>\d+)$‘, views.IndexView.as_view()), ] class IndexView(views.APIView): def get(self,request,*args,**kwargs): pk = kwargs.get(‘pk‘) if pk: pass # 获取单条信息 else: pass # 获取列表信息 def post(self,request,*args,**kwargs): pass def put(self,request,*args,**kwargs): pass def patch(self,request,*args,**kwargs): pass def delete(self,request,*args,**kwargs): pass 4.ModelViewSet(mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet) #继承了 增删改查+局部更新+GenericViewSet from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination,CursorPagination from rest_framework import viewsets from api import models from api.serializers.index import IndexSerializer class P2(PageNumberPagination): # 每页显示的数据条数 max_page_size = 5 page_size = 2 page_size_query_param = ‘size‘ # 页码 page_query_param = ‘page‘ class IndexView(viewsets.ModelViewSet): #也可以不继承ModelViewSet,继承上面那些类中的几个,就只有某几个方法了 queryset = models.UserInfo.objects.all() serializer_class = IndexSerializer pagination_class = P2 #也可以自定制方法 # def list(self, request, *args, **kwargs): # pass # def retrieve(self, request, *args, **kwargs): # pass