简单点说,DRF的Viewsets就允许你将一批功能类似或者有流程的接口写在一个类里面。
比如我有一个流程:需要先A, 后B,再C,后D,完成4个顺序接口,则可以这样使用Viewsets。
from rest_framework import viewsets
from rest_framework.decorators import list_route
class UserViewSet(viewsets.GenericViewSet):
"""
A viewset that provides the standard actions
"""
@list_route(methods=['post'])
def A(self, request):
return Response('A')
@list_route(methods=['get'])
def B(self, request):
return Response('B')
@list_route(methods=['post'])
def C(self, request):
return Response('C')
@list_route(methods=['get'])
def D(self, request):
return Response('D')
from django.conf.urls import url
from rest_framework.routers import DefaultRouter
from rs_account.views import (
UserViewSet
)
router = DefaultRouter()
router.register(r'user', UserViewSet, base_name='user')
urlpatterns = [
# search question
]
urlpatterns += router.urls
这样配置完,你就有4个接口URL:
post /user/A/
get /user/B/
post /user/C/
get /user/D/
根据最新的官方文档,在DRF 3.8这个版本使用 @action 代替了 @list_router和@detail_router。
Deprecations
action decorator replaces list_route and detail_route
#5705 list_route and detail_route have been merge into a single action decorator. This improves viewset action introspection, and will allow extra actions to be displayed in the Browsable API in future versions.
Both list_route and detail_route are now pending deprecation. They will be deprecated in 3.9 and removed entirely in 3.10.
The new action decorator takes a boolean detail argument.
Replace detail_route uses with @action(detail=True).
Replace list_route uses with @action(detail=False).