How to cache Django Rest Framework API calls?

Ok, so, in order to use caching for your queryset:

class ProductListAPIView(generics.ListAPIView):
    def get_queryset(self):
        return get_myobj()
    serializer_class = ProductSerializer

You’d probably want to set a timeout on the cache set though (like 60 seconds):

cache.set(cache_key, result, 60)

If you want to cache the whole view:

from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page

class ProductListAPIView(generics.ListAPIView):
    serializer_class = ProductSerializer

    @method_decorator(cache_page(60))
    def dispatch(self, *args, **kwargs):
        return super(ProductListAPIView, self).dispatch(*args, **kwargs)

Leave a Comment