ssm
ssm

Reputation: 650

Invoke function after all methods Django Rest Framework ModelViewSet

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.

Upvotes: 1

Views: 1196

Answers (2)

JPG
JPG

Reputation: 88689

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

Upvotes: 2

Faisal Manzer
Faisal Manzer

Reputation: 2129

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.

Upvotes: 1

Related Questions