John
John

Reputation: 299

Django + Disable Caching for extended viewset

How to disable Django Cacheing for one of the viewset in below scenario ? I want to disable caching for viewset with name SecondViewSet, I am using @method_decorator(never_cache, name="list") on SecondViewSet it is not working, kindly advise

Abstract Viewset

class AbstractDataViewSet(ListAPIView):
    http_method_names = ['get', 'options']
    permission_classes = [IsAuthorizedUser]

    @method_decorator(cache_page(settings.VIEWSET_CACHE_TIMEOUT))
    def list(self, request, *args, **kwargs):
        return Response(data={"message":"appdata"}

First Viewset

class FirstViewSet(AbstractDataViewSet):
    group_permissions = {
        'GET': (
            roles.ACCOUNTING,
        )
    }

Second Viewset

class SecondViewSet(AbstractDataViewSet):
    group_permissions = {
        'GET': (
            roles.ACCOUNTING,
        )
    }

Third Viewset

class ThirdViewSet(AbstractDataViewSet):
    group_permissions = {
        'GET': (
            roles.ACCOUNTING,
        )
    }

Upvotes: 0

Views: 367

Answers (1)

sytech
sytech

Reputation: 41159

If the decorator appropriately uses functools.wraps or similar, you should be able to access the __wrapped__ attribute and, effectively, undo the decorator.

class SecondViewSet(AbstractDataViewSet):
    list = AbstractDataViewSet.list.__wrapped__

Alternatively, you can have another method separate from the decorated method that you delegate to from your list method. Then, simply redefine the method in the subclass to define it without the decorator.


class AbstractDataViewSet(ListAPIView):
    http_method_names = ['get', 'options']
    permission_classes = [IsAuthorizedUser]
    def _list(self, request, *args, **kwargs):
        return Response(data={"message":"appdata"}
    @method_decorator(cache_page(settings.VIEWSET_CACHE_TIMEOUT))
    def list(self, request, *args, **kwargs):
        return self._list(request, *args, **kwargs)

...

class SecondViewSet(AbstractDataViewSet):
    # define list again to avoid caching decorator
    def list(self, request, *args, **kwargs):
        return self._list(request, *args, **kwargs)

These approaches should work without having to change the implementation of the decorator. Another approach might be to change the implementation of the decorator to inspect class attributes to determine which methods should be cached.

Upvotes: 1

Related Questions