将ListCreateAPIView-class添加到路由器

时间:2015-02-12 08:08:33

标签: 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(model=Car), name='cars'),

我想添加这个Cars-view(如果我手动调用url,它正在按预期工作!)到路由器,所以它在概述页面中!

所以:它按原样运行,但我必须手动输入网址,它不在API的概述页面中。

1 个答案:

答案 0 :(得分:4)

原因是ViewSet类与路由器配合使用的是GenericViewSet,其基数为ViewSetMixin
ViewSetMixin覆盖as_view()方法,以便actions关键字执行HTTP方法绑定到资源上的操作,路由器可以为操作方法构建映射。
您可以通过简单地在类库中添加mixin来解决它:

from rest_framework.viewsets import ViewSetMixin

class CarList(ViewSetMixin, generics.ListCreateAPIView)
    ....

但目前尚不清楚解决方案,因为ListCreateAPIViewModelViewSet它只是一个基类中有一堆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

注意相同的mixins ListModelMixinCreateModelMixin只有GenericViewSetGenericAPIView的区别。
GenericAPIView使用方法名称并在其中调用操作。 GenericViewSet改为使用操作并将其映射到方法 这里的ViewSet包含您需要的方法:

class ListCreateViewSet(mixins.ListModelMixin,
                    mixins.CreateModelMixin,
                    GenericViewSet):   

    queryset_class = ..
    serializer_class = ..

现在它可以与路由器配合使用,如果您需要特殊行为,可以覆盖listcreate方法。

相关问题