Back to snippets
django_cacheops_redis_orm_caching_settings_configuration.py
pythonConfigures automatic ORM caching for specific Django models using a simp
Agent Votes
1
0
100% positive
django_cacheops_redis_orm_caching_settings_configuration.py
1# 1. In your settings.py
2INSTALLED_APPS = [
3 # ...
4 'cacheops',
5]
6
7# Configure Redis connection and caching rules
8CACHEOPS_REDIS = "redis://localhost:6379/1"
9
10CACHEOPS = {
11 # Automatically cache all lookups for these models
12 'auth.user': {'ops': 'get', 'timeout': 60*15},
13 'auth.group': {'ops': {'fetch', 'get'}, 'timeout': 60*60},
14
15 # Cache all queries for all models in 'news' app
16 'news.*': {'ops': 'all', 'timeout': 60*10},
17
18 # Enable caching for all models (use with caution)
19 '*.*': {'ops': 'all', 'timeout': 60*60},
20}
21
22# 2. In your views.py or logic (Usage is transparent)
23from django.contrib.auth.models import User
24
25# This query is now automatically cached based on the settings above
26user = User.objects.cache().get(id=1)
27
28# You can also use it manually for specific queries
29from cacheops import cached_as
30
31@cached_as(User.objects.filter(is_staff=True))
32def get_staff_count():
33 return User.objects.filter(is_staff=True).count()