2015-02-12 89 views
4

如何添加一個ListCreateAPIView到路由器的URL?添加ListCreateAPIView類到路由器

通常我不喜歡:

router = routers.DefaultRouter() 
router.register(r'busses', BusViewSet) 

但現在我有:

class CarList(generics.ListCreateAPIView): ... 

我把它添加到URL模式現在:

urlpatterns = patterns('', 
url(r'^carts/', CarList.as_view(model=Car), name='cars'), 

,我想補充這個Cars-view(如果我手動調用url,它會按預期工作!)到路由器,所以它在概述頁面中!

所以:它的工作原理,因爲它是,但我必須手動輸入網址,它不是在API的概述頁。

+0

你有沒有找到這個解決方案? – 2017-02-16 21:42:02

回答

3

原因是爲什麼一個ViewSet類與路由器工作是一個GenericViewSet其中有一個ViewSetMixin在一個基地。
ViewSetMixin倍率as_view()方法,使得它需要執行的HTTP方法的結合對資源和路由器可以建立一個地圖爲行動的方法的動作的actions關鍵字。
您可以通過簡單的解決它補充說,在混入一類基地:

from rest_framework.viewsets import ViewSetMixin 

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

但目前尚不清楚解決方案,因爲ListCreateAPIViewModelViewSet它只是一個空班,在基地一堆混入的。所以你總是可以用你需要的方法建立你自己的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 

注意同一混入ListModelMixinCreateModelMixin存在GenericViewSetGenericAPIView唯一的區別。
GenericAPIView使用方法名稱並調用其中的操作。 GenericViewSet改爲使用操作並將它們映射到方法。
這裏ViewSet與方法,你需要:

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

    queryset_class = .. 
    serializer_class = .. 

現在它將會與路由器工作,如果你需要一個特殊的行爲,您可以覆蓋listcreate方法。