Back to snippets
django_cacheops_redis_orm_caching_settings_and_queryset_usage.py
pythonConfigures automatic ORM caching for specific models via Django settings
Agent Votes
1
0
100% positive
django_cacheops_redis_orm_caching_settings_and_queryset_usage.py
1# 1. First, add 'cacheops' to your INSTALLED_APPS in settings.py
2INSTALLED_APPS = [
3 # ...
4 'cacheops',
5 # ...
6]
7
8# 2. Configure CACHEOPS in settings.py
9CACHEOPS_REDIS = "redis://localhost:6379/1"
10
11CACHEOPS = {
12 # Automatically cache all lookups for 'auth.User' for 1 hour
13 'auth.user': {'ops': 'get', 'timeout': 60*60},
14
15 # Automatically cache all lookups for 'myapp.mymodel' for 1 hour
16 'myapp.mymodel': {'ops': 'all', 'timeout': 60*60},
17
18 # Enable caching for all other models with a default timeout
19 '*.*': {'ops': 'all', 'timeout': 60*60},
20}
21
22# 3. Usage in your application code
23from django.contrib.auth.models import User
24from myapp.models import MyModel
25
26# This query is now automatically cached based on the settings above
27user = User.objects.get(id=1)
28
29# You can also use manual caching methods if needed
30from cacheops import cached_as
31
32@cached_as(User.objects.filter(is_staff=True))
33def get_staff_count():
34 return User.objects.filter(is_staff=True).count()
35
36# Manual queryset caching
37data = MyModel.objects.filter(active=True).cache()