1

I would like to invoke a function after all methods in a ModelViewSet. The function itself will be used as an external event log. So the response from the views would not be modified. I was not able to figureout how to achieve this. My ModelViewSet is a very basic one with serializer class and queryset defined.

Any help would be appreciated.

ssm
  • 620
  • 6
  • 24

2 Answers2

2

Override the dispatch method of view.

class MyDRFView(...):

    def my_custom_logging_method(self, request, response, *args, **kwargs):
        # do something useful here.....
        ...

    def dispatch(self, request, *args, **kwargs):
        response = super().dispatch(request, *args, **kwargs)
        self.my_custom_logging_method(request, response, *args, **kwargs)
        return respons
JPG
  • 82,442
  • 19
  • 127
  • 206
1

You can always override any python class. Overriding all the method can be little trickier and I guess will just create unnecessary logs. You should only override the method that is really of importance. Here is an example:

class LoggingModelViewSet(viewsets.ModelViewSet):
    def perform_create(self, serializer):
        print('Invoked perform_create')
        serializer.save(owner=self.request.user)

    def finalize_response(self, request, response, *args, **kwargs):
        xresponse = super().finalize_response(request, response, *args, **kwargs)

        print('finalize_response', xresponse)
        return xresponse

and more like this... you should see the source here https://github.com/encode/django-rest-framework/blob/master/rest_framework/viewsets.py#L217 It is not so tricky.

Faisal Manzer
  • 2,089
  • 3
  • 14
  • 34
  • I found a workaround with overriding finalize_response method. This has both request and response. Is there a better way? – ssm Dec 14 '19 at 01:01
  • This is not any workaround this is what you will really do. I am editing the post with your example. – Faisal Manzer Dec 14 '19 at 01:03
  • Why did you add **`perform_create`** here? It will probably create confusion here. – JPG Dec 14 '19 at 01:47
  • Just for example. Question was to log every function call so I added `perform_create`. If you feel for a better example edit the answer :) – Faisal Manzer Dec 14 '19 at 01:49