How to cache ClassBasedAPIViews in Django Rest Framework?

Viewed 486

I am serving list of products in DRF and I tried to use cache in ClassBasedApiViews,
urls.py

path('',ProductListAPIView.as_view(), name='products') 

views.py:

class ProductListAPIView(ListAPIView):
        permission_classes = [IsAuthenticated]
        queryset = Product.objects.all()
        serializer_class = ProductSerializer

serializers.py:

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'
        depth = 1

There is no function like def get() ... So I can not use conventional decorator before the function to cache.

What I have tried is path('', cache_page(300)(ProductListAPIView.as_view()), name='products') this works.

In case of multiple decorators path('', vary_on_headers('Authorization')(cache_page(300)(ProductListAPIView.as_view())), name='products') works as well.

Is there a better way to use both decorators cache_page and vary_on_headers for ClassBasedAPIView?

0 Answers
Related