8

I am aware of https://github.com/chibisov/drf-extensions but the build is failing.

How should responses be cached for generic views? For example:

class PropertyList(generics.ListAPIView):

    queryset = Property.objects.all().prefetch_related("photos")
    serializer_class = PropertyListSerializer


    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('featured', 'state', 'price_cents','location', 'status')
    ordering_fields = ('expiration_date',)

Is implementing the list method from the ListModelMixin the only option?

ajaxon
  • 666
  • 2
  • 9
  • 20

1 Answers1

2

There are some solutions for that:

  • You can use Cache for APIview and ViewSets with decorators like cache_page or vary_on_cookie. like below:

    class UserViewSet(viewsets.Viewset):
    
    # Cache requested url for each user for 2 hours
    @method_decorator(cache_page(60*60*2))
    @method_decorator(vary_on_cookie)
    def list(self, request, format=None):
        content = {
            'user_feed': request.user.get_user_feed()
        }
        return Response(content)
    

    read More about it in Django rest original page for caching

  • You can also do it in your own way. I mean you can just use cache methods provided in django like cache.set. for example to store just result of a method or a query and store for furture requests, you can just define a key for it and set that result to that key with cache.set(cache_key, result, expire_time) and then get it whenever you want. So just if the cache was available for that key, then fetch else then again fetch result from database and store it again.

    By the way it's almost a duplicate of this link on stackoverflow

Remember you should define a cache backend for your results. by default you can use database backend to store results with keys on database or file system. But a proper and better solution is to use message brokers like redis or memcached or ... based on your needs.

here are some other useful links:

Reza Torkaman Ahmadi
  • 2,958
  • 2
  • 20
  • 43