Django 将ListCreateAPIView类添加到路由器
如何将ListCreateAPIView添加到路由器URL 通常我喜欢:Django 将ListCreateAPIView类添加到路由器,django,django-rest-framework,Django,Django Rest Framework,如何将ListCreateAPIView添加到路由器URL 通常我喜欢: router = routers.DefaultRouter() router.register(r'busses', BusViewSet) 但现在我有: class CarList(generics.ListCreateAPIView): ... 我现在将其添加到urlpatterns中: urlpatterns = patterns('', url(r'^carts/', CarList.as_view(mod
router = routers.DefaultRouter()
router.register(r'busses', BusViewSet)
但现在我有:
class CarList(generics.ListCreateAPIView): ...
我现在将其添加到urlpatterns中:
urlpatterns = patterns('',
url(r'^carts/', CarList.as_view(model=Car), name='cars'),
我想把这个Cars视图添加到路由器中(如果我手动调用url,它会正常工作!),所以它在概览页面中
所以:它按原样工作,但我必须手动输入url,它不在API的概览页面中。原因是
ViewSet
类与路由器一起工作的是GenericViewSet
,它在一个基中有一个ViewSetMixin
。ViewSetMixin
overrideas_view()
方法,以便它采用actions
关键字,执行HTTP方法与资源上的操作的绑定,路由器可以为action方法构建映射。您可以通过简单地在类中添加mixin来解决此问题:
from rest_framework.viewsets import ViewSetMixin
class CarList(ViewSetMixin, generics.ListCreateAPIView)
....
但这并不是一个明确的解决方案,因为listcreateapieview
和ModelViewSet
它只是一个空类,在一个基类中有一堆混合。因此,您始终可以使用所需的方法构建自己的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)
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet):
pass
这里是ModelViewSet
:
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)
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet):
pass
请注意,相同的mixinListModelMixin
和CreateModelMixin
只有GenericViewSet
和GenericAPIView
之间的区别GenericAPIView
使用方法名并在其中调用操作<代码>通用视图集改为使用操作并将其映射到方法。下面是
视图集
,其中包含您需要的方法:
class ListCreateViewSet(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericViewSet):
queryset_class = ..
serializer_class = ..
现在,它将与路由器一起工作,如果您需要特殊行为,您可以覆盖
列表
和创建
方法。您找到过解决方案吗?