django-redis
django-redis is a full-featured Redis cache backend for Django, providing robust integration with Redis as Django's caching system. The current version is 6.0.0, released in June 2025, and it typically sees several updates per year, following Django's release cycle.
Warnings
- gotcha When using `redis-py` version 5.0 or newer with `hiredis` installed, you must explicitly set `PARSER_CLASS` in `CACHES OPTIONS` to `redis.connection.HiredisParser` for `hiredis` to be utilized correctly. Failure to do so may result in `hiredis` not being used, impacting performance.
- breaking Always verify `django-redis` compatibility with your specific Django version. New `django-redis` versions often introduce support for newer Django versions, while dropping support for older ones. For example, Django 4.x support was added in `django-redis` 5.3.0.
- gotcha By default, `django-redis` uses Python's `pickle` module for serialization. This can pose security risks if untrusted data is deserialized, and limits interoperability with non-Python clients or services that expect common formats like JSON.
- gotcha Incorrect `LOCATION` string format or inaccessible Redis server can lead to `ConnectionError` or `TimeoutError`. The format is crucial (e.g., `redis://host:port/db_number`).
Install
-
pip install django-redis -
pip install django-redis hiredis
Imports
- RedisCache
from django_redis.cache import RedisCache
Quickstart
# settings.py
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
# For redis-py >= 5.0 with hiredis:
# "PARSER_CLASS": "redis.connection.HiredisParser",
"SERIALIZER": "django_redis.serializers.json.JSONSerializer" # Example of changing serializer
}
}
}
# app_name/views.py or similar
from django.core.cache import cache
def my_view(request):
value = cache.get('my_key')
if value is None:
value = 'data_from_db'
cache.set('my_key', value, timeout=300) # Cache for 5 minutes
return f"<h1>Cached Value: {value}</h1>"