Privacy Policy
Snippets index

  Sample usage of Django’s in-built cache framework

from django.core.cache import cache
from .models import Article

def get_articles():
    cached_data = cache.get('articles')
    if cached_data is not None:
        return cached_data
    data = Article.objects.all()
    cache.set('articles', data, 3600)

    return data

In the code above, I first checked if articles is cached using cache.get(). If it's in the cache, return the cached articles. Otherwise, retrieve the articles from the database, store it in the cache using cache.set(), and then return it. The articles will remain in the cache for 1 hour (3600 seconds).