Home > Net >  write custom functions inside generic class based view in django rest framework
write custom functions inside generic class based view in django rest framework

Time:02-27

I have to write a custom function inside class based view which is like below:

class ExampleView(ListCreateAPIView,
                  UpdateAPIView,
                 DestroyAPIView):
    queryset = Example.objects.all()
    serializer_class = ExampleSerializer
    

    def get(self, request, *args, **kwargs):
        /.........some code............./

    def random_custom(self, request, *args, **kwargs):
        /.........some code............./

Here above I have a random custom function which I need to call from the url. Now I am not sure how to do that. If it was a modelviewset, we can do it easily like this:

path("example/",users.ExampleView.as_view({"get": "random_custom"}),
     ),

I have done it before in ModelVIewset,ie call custom functions like above but I am not sure how to do that is genericviews like above.

CodePudding user response:

Have you tried putting random_custom() into get() method? It should be executed right after GET method is initialised by client.

class ExampleView(...):
    ...
    

    def get(self, request, *args, **kwargs):
        self.random_custom()
        /.........some code............./

    def random_custom(self, request, *args, **kwargs):
        /.........some code............./

CodePudding user response:

The code which makes the decision about which method on your APIView-derived class to call is in APIView.dispatch(). You can read the source here.

Here's how it works:

  1. Convert the method name (e.g. GET, POST, OPTIONS) to lowercase. Check that the method name is a valid HTTP method. If not, return an error code.
  2. Check if the object defines a lowercase version of the method name. If not, return an error code.
  3. Use getattr() to get that method, and call it.

This means that there are only two ways to redirect the call from get().

  1. Define get() and make it call random_custom(), as @NixonSparrow describes.
  2. Override the dispatch() method to call something else.

Those are the only two ways to do it.

  • Related