汇总
2个视图基类
5个视图拓展类
9个视图子类、视图集、路由组件
2个视图基类
APIView
from rest_framework.views import APIView
GenericAPIView
from rest_framework.generics import GenericAPIView
5个视图拓展类
需要注意的是:这5个视图拓展类,是拓展不是继承。
ListModelMixin # 获取所有
CreateModelMixin # 创建一个
RetrieveModelMixin # 查询一个
UpdateModelMixin # 更新一个
DestroyModelMixin # 删除一个
ListModelMixin # 获取所有
ListModelMixin # 获取所有
CreateModelMixin
CreateModelMixin # 创建一个
RetrieveModelMixin
RetrieveModelMixin # 查询一个
UpdateModelMixin
UpdateModelMixin # 更新一个
DestroyModelMixin
DestroyModelMixin # 删除一个
9个视图子类
继承自 5个视图拓展类 + GenericAPIView
进行视图拓展类的组合
GenericAPIView
# 获取所有,新增一个,获取所有和新建一个
ListAPIView,CreateAPIView,ListCreateAPIView
5个视图拓展类
# 获取单个,更新一个,删除一个
RetrieveAPIView,UpdateAPIView,DestroyAPIView
RetrieveUpdateDestroyAPIView,RetrieveUpdateAPIView,RetrieveDestroyAPIView
# 继承9个视图子类后,只需要在视图类中写两个类属性即可
queryset =
serializer_class =
GenericAPIView对应的
ListAPIView,CreateAPIView,ListCreateAPIView
5个视图拓展类对应的
# 获取单个,更新一个,删除一个
RetrieveAPIView,UpdateAPIView,DestroyAPIView
RetrieveUpdateDestroyAPIView,RetrieveUpdateAPIView,RetrieveDestroyAPIView
视图集
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet):
pass# 五个视图拓展类:
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
每个类里有一个方法
create retrieve update destroy list
# GenericViewSet
ViewSetMixin + generics.GenericAPIView
2个视图基类之一
# ViewSetMixin
继承后,路由写法发生变化
as_view({'get': 'list', 'post': 'create'})
# 视图集中的类
ViewSetMixin # 改变路由写法 可自定义路由
ViewSet 继承了'ViewSetMixin' + 'views.APIView'
自定义路由 + APIView
GenericViewSet 继承了'ViewSetMixin' + 'generics.GenericAPIView'
自定义路由 + GenericAPIView
ReadOnlyModelViewSet 继承了'mixins.RetrieveModelMixin' + 'mixins.ListModelMixin' + 'GenericViewSet'
查单个 + 查全部 + 自定义路由 + GenericAPIView
ModelViewSet 继承了'五个视图拓展类' + 'GenericViewSet'
全继承 自定义路由 + GenericAPIView
参考链接:非原创
本文来自博客园,作者:topass123,转载请注明原文链接:https://www.cnblogs.com/topass123/p/16730400.html