Django-rest-framework @detail_route for specific u

2019-05-27 05:59发布

问题:

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:

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.