特定网址的Django-rest-framework @detail_route [英] Django-rest-framework @detail_route for specific url
问题描述
我正在使用 Django-rest-framework == 3.3.2
和 Django == 1.8.8
。我有一个简单的 GenericView
从rest_framework导入泛型
从rest_framework.decorators导入detail_route
类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)
#做一些重要的事情
return Response()
如果我使用<$ django-rest-framework提供的c $ c> router ,但是我手动创建了所有网址,并希望对 detail_route $ c $做同样的操作c>。
我想知道我是否可以做这样的事情:
from django.conf.urls导入模式,myapi导入视图中的url
urlpatterns = pattern(
'',
url(r'^ my-api / $' ,views.MyApiView.as_view()),
url(r'^ my-api / action $',views.MyApiView.custom_action.as_view()),
)
当然,第二个网址不起作用。
预先感谢。
按照根据视图集文档中的示例,您可以将各个方法提取到视图中:
custom_action_view = views.MyApiView.as_view({ post: custom_action })
然后,您可以自由地按常规方式进行路由:
urlpatterns = [
url(r'^ my-api / action $',custom_action_view),
]
我希望能帮上忙。
I'm using Django-rest-framework==3.3.2
and Django==1.8.8
. I have a simple 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()
This works fine if I use the router
that django-rest-framework offers, however I'm creating all my urls manually and would like to do the same with the detail_route
.
I wonder if it's possible for me to do something like this:
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()),
)
Of course this second url doesn't work. It's just an example of what I would like to do.
Thanks in advance.
As per the example from the Viewsets docs, you can extract individual methods into views:
custom_action_view = views.MyApiView.as_view({"post": "custom_action"})
You're then free to route this as normal:
urlpatterns = [
url(r'^my-api/action$', custom_action_view),
]
I hope that helps.
这篇关于特定网址的Django-rest-framework @detail_route的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!