Django-rest-framework @detail_route用于特定网址

时间:2016-02-22 12:50:05

标签: python django django-rest-framework

我正在使用Django-rest-framework==3.3.2Django==1.8.8。我有一个简单的GenericView

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-framework提供的router,这可以正常工作,但我手动创建所有网址,并希望对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()),

当然第二个网址不起作用。这只是我想做的一个例子。

提前致谢。

1 个答案:

答案 0 :(得分:4)

作为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),
]

我希望有所帮助。