一.先看原码:
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet):
"""
A viewset that provides default `create()`, `retrieve()`, `update()`,
`partial_update()`, `destroy()` and `list()` actions.
"""
pass
二.使用:
因为继承关系为ModelViewSet < GenericViewSet < GenericAPIView。
GenericAPIView内必须定义属性:queryset 和 serializer_class
所以ModelViewSet 通常结合 ModelSerializer 使用
class ProjectTypeSerializer(serializers.ModelSerializer):
"""项目类型序列化器"""
class Meta:
model = ProjectType
fields = '__all__'
from rest_framework.decorators import action
class ProjectTypeViewSet(ModelViewSet):
#permission_classes = (IsAuthenticated,)
queryset = ProjectType.objects.filter(is_delete=0).all().order_by('-id')
serializer_class = ProjectTypeSerializer
#自定义方法
@action(methods=['get','post'], detail=False, url_path='user_action')
def user_action(self,request, *args, **kwargs):
dd = {"w":"ww","ee":"ttt"}
return Response(dd)
三.路由配置:
from rest_framework.routers import DefaultRouter
from . import views
app_name = 'app1'
router = DefaultRouter() # 可以处理视图的路由器
router.register(r'projects', views.ProjectTypeViewSet)
urlpatterns = [
#url(r'^configyml/$', views.configYml),
]
urlpatterns += router.urls
四.访问:
由于modelviewset也集成了mix相关类所以有get,post,delete, put相关对应的方法
请求 |
url |
对应方法 |
备注 |
get |
127.0.0.1:8000/projects/ |
list |
ListModelMixin |
get |
127.0.0.1:8000/projects/{1}/ |
retrieve |
....Mixin |
post |
127.0.0.1:8000/projects/ |
create |
....Mixin |
put |
127.0.0.1:8000/projects/{1}/ |
update |
....Mixin |
detete |
127.0.0.1:8000/projects/{1}/ |
destroy |
....Mixin |
get |
127.0.0.1:8000/projects/ useraction |
useraction |
自定义 |
post |
127.0.0.1:8000/projects/ useraction |
useraction |
自定义 |
五.补充 @action中 detail=True 则表示对某个具体实例操作:
127.0.0.1:8000/projects/{id}/user_action