📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Django Framework Django Caching

Django Caching

5 min read
Cache views, template fragments, and querysets with Django's cache framework and Redis.

Django Caching

# settings.py
CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
    }
}

from django.core.cache import cache
from django.views.decorators.cache import cache_page

# Cache whole view (5 minutes)
@cache_page(60 * 5)
def post_list(request):
    pass

# Cache fragment in template
{% load cache %}
{% cache 300 "sidebar" %}
    ... expensive content ...
{% endcache %}

# Low-level cache
cache.set("my_key", {"data": [1,2,3]}, timeout=3600)
value  = cache.get("my_key", default=[])
cache.delete("my_key")

# Cache-or-fetch
posts = cache.get_or_set("all_posts", lambda: list(Post.objects.all()), 3600)