While using Cache In DRF after using POST request new data is not being displayed on client side

Question:

I have implemented cache for my articles views, and have set cache page. Currently the issue that i am facing is when i try to POST request data to create new article, the page remains the same.

What i want to do is be able to POST article while i am still in cache page time, and display the new data while being in the cache page time.

following is the cache page code …

articles views

class ArticleViewSet(viewsets.ModelViewSet):
    
    serializer_class=ArticleSerializer
    permission_classes=[permissions.IsAuthenticated]
    authentication_classes = [authentication.TokenAuthentication]

    
    @method_decorator(cache_page(300))
    @method_decorator(vary_on_headers("Authorization",))
    def dispatch(self, *args, **kwargs):
       return super(ArticleViewSet, self).dispatch(*args, **kwargs)

Someone can guide how can i achieve this …

Asked By: Abdullah Roshan

||

Answers:

You can’t.

Cache pages are intended to be static responses, unchanged for the duration of the cache. That’s the whole point.

If you want updated content after a POST, you need to not cache that view at all.

Instead, you could cache individual objects in the viewset, using Django’s per-view caching. That will allow individual objects to be invalidated from the cache when they are updated, giving you fresh data after POST requests, while still caching most of the content.

Note however that caching viewsets is somewhat fraught, as the various list, detail, create etc. views all use the same URL, but have very different caching requirements.

Generally, REST API endpoints are not great candidates for caching in the first place. The overhead of serialization and deserialization, and the highly dynamic nature of the content, often outweighs any gains from caching.

Answered By: Mohsin Maqsood