视图: a. django class Test(View): ... b. rest_framework class Test(APIView): ... c. GenericAPIView 一般不用这个类来做视图 from rest_framework.generics import GenericAPIView class ViewView(GenericAPIView): queryset = models.Role.objects.all() serializer_class = PagerSerializer pagination_class = PageNumberPagination def get(self,reuqest,*args,**kwargs): #获取数据 models.Role.objects.all() roles = self.get_queryset() pager_roles = self.paginate_queryset(roles) #序列化 self.get_serializer(instance=pager_roles,many=True) return Response(ser.data) d. GenericViewSet(ViewSetMixin, generics.GenericAPIView) 继承两个父类 #需要路由传参数 url(r'^(?P<version>[v1|v2]+)/v1/$',views.ViewView.as_view({'get':'list','post':'post_list'})), #参数传递给 ViewView get方法执行list post方法执行post_list from rest_framework.viewsets import GenericViewSet class ViewView(GenericViewSet): def list(self,request,*args,**kwargs): return Response('GET') def post_list(self,request,*args,**kwargs): return Response('POST') e. ModelViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.updateModelMinxin, mixins.DestroyModelMinxin, mixins.ListModelMixin, GenericViewSet) #需要路由传参数 url(r'^(?P<version>[v1|v2]+)/v1/(?P<pk>d+)/$',views.ViewView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})), # 继承ModelViewSet 所有的 增删改查的功能都有了 # 如果是get请求 retrieve获取单条数据 根据传的参数pk来查询 # 如果是delete请求 destroy删除数据 # 如果是put请求 update更新数据 # 如果是patch请求 partial_update 部分更新数据 # list 查询所有数据 # create 增加数据 # 需要关注路由系统 {'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'} {'get':'list','post':'post_list'} from rest_framework.viewsets import ModelViewSet class ViewView(ModelViewSet): queryset = models.Role.objects.all() serializer_class = PagerSerializer pagination_class = PageNumberPagination 总结: - 大部分使用 APIView - 也可以使用 GenericViewSet 在路由中区分get,post - 基本的增删改查实现 继承 ModelViewSet - 增删 继承GenericViewSet, CreateModelMixin,DestroyModelMinxin - 复杂逻辑 继承GenericViewSet 或者 APIView