Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 659
Marcelo Grebois Avatar asked Jan 08 '23 21:01

Marcelo Grebois


2 Answers

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.

like image 198
ncopiy Avatar answered Jan 15 '23 07:01

ncopiy


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..
like image 30
pro- learner Avatar answered Jan 15 '23 08:01

pro- learner