2016-02-22 26 views
2

我使用的是Django-rest-framework==3.3.2Django==1.8.8。我有一個簡單GenericView特定網址的Django-rest-framework @detail_route

from rest_framework import generics 
from rest_framework.decorators import detail_route 

class MyApiView(generics.RetrieveAPIView): 
    serializer = MySerializer 
    def get(self, *args, **kwargs): 
     super(MyApiView, self).get(*args, **kwargs) 

    @detail_route(methods=['post']) 
    def custom_action(self, request) 
     # do something important 
     return Response() 

如果我使用Django的REST的框架提供了router,但是我手動創建我的所有URL,並希望做的detail_route同這工作得很好。

我不知道是否有可能對我來說,做這樣的事情:

from django.conf.urls import patterns, url 
from myapi import views 
urlpatterns = patterns(
    '', 
    url(r'^my-api/$', views.MyApiView.as_view()), 
    url(r'^my-api/action$', views.MyApiView.custom_action.as_view()), 

當然,這第二個URL不起作用。這只是我想要做的一個例子。

在此先感謝。

回答

3

由於per the example from the Viewsets docs,您可以提取單個方法到觀點:

custom_action_view = views.MyApiView.as_view({"post": "custom_action"}) 

你就可以自由地航線這是正常的:

urlpatterns = [ 
    url(r'^my-api/action$', custom_action_view), 
] 

我希望幫助。

+0

這就像一個魅力!感謝你的回答! – jarussi

+0

不客氣:) –