原因是 ViewSet 类与路由器一起工作的原因是 GenericViewSet 在基数中有一个 ViewSetMixin。
ViewSetMixin 覆盖 as_view() 方法以便它采用 actions将 HTTP 方法绑定到资源和路由器上的操作的关键字可以为操作方法构建映射。
您可以通过在类库中简单地添加该 mixin 来解决它:
from rest_framework.viewsets import ViewSetMixin
class CarList(ViewSetMixin, generics.ListCreateAPIView)
....
但这不是一个明确的解决方案,因为ListCreateAPIView 和ModelViewSet 它只是一个空类,在一个基础中有一堆mixin。因此,您始终可以使用所需的方法构建自己的 ViewSet。
比如这里ListCreateAPIView的代码:
class ListCreateAPIView(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
这里是ModelViewSet:
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet):
pass
注意 ListModelMixin 和 CreateModelMixin 相同的 mixin,GenericViewSet 和 GenericAPIView 之间只有区别。
GenericAPIView 使用方法名称并在其中调用操作。 GenericViewSet 改为使用操作并将它们映射到方法。
这里ViewSet 带有您需要的方法:
class ListCreateViewSet(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericViewSet):
queryset_class = ..
serializer_class = ..
现在它将与路由器一起使用,如果您需要特殊行为,您可以覆盖 list 和 create 方法。