Django API with Redis Cache Not Updating Immediately After POST/PUT/DELETE Requests

I'm developing a Django REST API using Django, Redis, and SQLite. The goal is to cache data for GET requests to improve performance, using Redis as the caching layer.

Issue:
When I create, update, or delete Category or Product instances, the changes are reflected in the database (as seen on the Django admin page), but not immediately in subsequent GET requests. The GET responses only reflect the changes after I restart the server. However, creating a new category with the same name is prevented, indicating the API can still read existing data from the database.

app/views.py

from django.shortcuts import render
from django.core.cache import cache
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from .models import Category, Product
from .serializers import CategorySerializer, ProductSerializer
from django.conf import settings

CACHE_TTL = getattr(settings, 'CACHE_TTL', 5)

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    cache_key = 'store:categories'

    def list(self, request, *args, **kwargs):
        data = cache.get(self.cache_key)
        print("Cache GET for"+self.cache_key)

        if not data:
            # Serialize the queryset to JSON before caching
            data = list(self.queryset);
            cache.set(self.cache_key, data, CACHE_TTL)
            print(f"Cache set for"+self.cache_key)

        print('Cache retrieved')
        serializer = self.get_serializer(data, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        cache.delete('store:categories')
        print(f"Cache deleted for"+self.cache_key)
        return super().create(request, *args, **kwargs)

    def update(self, request, *args, **kwargs):
        cache.delete('store:categories')
        print(f"Cache deleted for"+self.cache_key)
        return super().update(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        cache.delete('store:categories')
        print(f"Cache deleted for"+self.cache_key)
        return super().destroy(request, *args, **kwargs)

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

    def list(self, request, *args, **kwargs):
        cache_key = 'store:products'
        data = cache.get(cache_key)

        if not data:
            data = list(self.queryset)
            cache.set(cache_key, data, CACHE_TTL)

        serializer = self.get_serializer(data, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        cache.delete('store:products')
        return super().create(request, *args, **kwargs)

    def update(self, request, *args, **kwargs):
        cache.delete('store:products')
        return super().update(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        cache.delete('store:products')
        return super().destroy(request, *args, **kwargs)

app/serializers.py

from rest_framework import serializers
from .models import Category, Product

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = '__all__'

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

Here are the debugging output for the category POST and GET:

System check identified no issues (0 silenced).
November 19, 2024 - 17:07:00
Django version 5.1.3, using settings 'storeapi.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Cache GET forstore:categories
Cache set forstore:categories
Cache retrieved
[19/Nov/2024 17:07:03] "GET /api/categories/ HTTP/1.1" 200 296
Cache deleted forstore:categories
[19/Nov/2024 17:07:16] "POST /api/categories/ HTTP/1.1" 201 42
Cache GET forstore:categories
Cache set forstore:categories
Cache retrieved
[19/Nov/2024 17:07:20] "GET /api/categories/ HTTP/1.1" 200 296
Back to Top