我正在使用Django-rest-framework==3.3.2
和Django==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()
如果我使用router
,效果很好。 django-rest-framework 提供了这个功能,但是我正在手动创建所有网址,并且希望对 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()),
)
当然,第二个网址不起作用。这只是我想做的一个例子。
提前致谢。
最佳答案
如per the example from the Viewsets docs ,您可以将各个方法提取到 View 中:
custom_action_view = views.MyApiView.as_view({"post": "custom_action"})
然后您就可以像平常一样自由地路由:
urlpatterns = [
url(r'^my-api/action$', custom_action_view),
]
希望对您有所帮助。
关于python - Django-rest-framework @detail_route 用于特定网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35554173/