Mirza Delic
Mirza Delic

Reputation: 4349

Django rest framework url with suffix

I have with url:

api/v1/quote/ # list
api/v1/quote/1/ # detail

how can i make new url like this:

api/v1/quote/1/action

and to send post request on this url with parametre active true, so it will use id from url and active from post and then do that action?

Any example for this?

I have this urls code:

router = routers.DefaultRouter()
router.register(r'quote', QuoteViewSet)

and view:

class QuoteViewSet(viewsets.ModelViewSet):
    queryset = Quote.active.all()
    serializer_class = QuoteSerializer

    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('created_at',)

    http_method_names = ['get', 'post', 'head']

Upvotes: 4

Views: 775

Answers (1)

ilse2005
ilse2005

Reputation: 11439

If you are using a Viewset you can add extra action using the @detail_route and @list_route decorators (docs)

In your case it could look like this:

class QuoteViewSet(viewsets.ModelViewSet):
    queryset = Quote.active.all()
    serializer_class = QuoteSerializer

    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('created_at',)

    http_method_names = ['get', 'post', 'head']

    @detail_route(methods=['post'])
    def action(self, id):
       # put your code here

The new action method is created automatically be the DefaultRouter router and can be accesed through:

api/v1/quote/{id}/action

Upvotes: 4

Related Questions