Django-rest-framework @detail_route for specific u

2019-05-27 05:47发布

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.

1条回答
劳资没心,怎么记你
2楼-- · 2019-05-27 06:45

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.

查看更多
登录 后发表回答