但是如何添加来自 rest_framework.generics 包的路由器视图?
你没有。 ViewSets 为rest_framework.generics 添加了几个兼容层,以便与路由器一起使用。
我应该定制路由器 (http://www.django-rest-framework.org/api-guide/routers/#custom-routers) 吗?最佳做法是什么?
如果你想使用非视图集视图,你将不得不编写常规的 Django url。
我的感觉是真正的问题是完全不同的,可能是“我如何将视图集限制为仅某些操作”。
在这种情况下,ModelViewSet 的声明提供了答案:
class ViewSet(ViewSetMixin, views.APIView):
"""
The base ViewSet class does not provide any actions by default.
"""
pass
class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
"""
The GenericViewSet class does not provide any actions by default,
but does include the base set of generic view behavior, such as
the `get_object` and `get_queryset` methods.
"""
pass
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
如您所见,您可以通过选择所需的 mixins 并从 GenericViewSet 继承来专门化 ModelViewSet。