Marcelo Grebois
Marcelo Grebois

Reputation: 383

How to create 2 actions with same path but different HTTP methods DRF

So I'm trying to have different actions under the same method, but the last defined method is the only one that work, is there a way to do this?

views.py

class SomeViewSet(ModelViewSet):
    ...

    @detail_route(methods=['post'])
    def methodname(self, request, pk=None):
    ... action 1

    @detail_route(methods=['get'])
    def methodname(self, request, pk=None):
    ... action 2

Upvotes: 6

Views: 3692

Answers (2)

ncopiy
ncopiy

Reputation: 1604

The most rational method I've found here:

class MyViewSet(ViewSet):
    @action(detail=False)
    def example(self, request, **kwargs):
        """GET implementation."""

    @example.mapping.post
    def create_example(self, request, **kwargs):
        """POST implementation."""

That method provides possibility to use self.action inside of another viewset methods with correct value.

Upvotes: 13

pro- learner
pro- learner

Reputation: 121

Are you trying to have actions based on HTTP request type? like for post request execute action 1 and for get request execute action 2? If that's the case then try

def methodname(self, request, pk=None):
    if request.method == "POST":
        action 1..
    else 
        action 2..

Upvotes: 1

Related Questions