django-redis-caching
БесплатноБез исполняемых скриптовНе проверенDjango Redis caching with django-cacheops. This skill should be used when implementing caching, adding cache invalidation, optimizing API performance…
Об этом скилле
Django Redis Caching Skill
Implements Redis caching with django-cacheops for the DTX Django backend.
Quick Reference
Cacheops Configuration
All models use 1-hour cache timeout (configured in settings.py):
CACHEOPS = {
"tournament.tournament": {"ops": "all", "timeout": 60 * 60},
"tournament.team": {"ops": "all", "timeout": 60 * 60},
"app.customuser": {"ops": "all", "timeout": 60 * 60},
"tournament.game": {"ops": "all", "timeout": 60 * 60},
"draft.draft": {"ops": "all", "timeout": 60 * 60},
"draft.draftround": {"ops": "all", "timeout": 60 * 60},
"draft.draftoptions": {"ops": "all", "timeout": 60 * 60},
# ...abbreviated; the full block is CACHEOPS in backend/backend/settings.py
}
View Caching Pattern
from cacheops import cached_as
def list(self, request, *args, **kwargs):
cache_key = f"model_list:{request.get_full_path()}"
@cached_as(Model1, Model2, extra=cache_key, timeout=60 * 60)
def get_data():
queryset = self.filter_queryset(self.get_queryset())
serializer = self.get_serializer(queryset, many=True)
return serializer.data
return Response(get_data())
Cache Invalidation Pattern
Preferred: invalidate_after_commit — use inside transactions, signal handlers, or anywhere writes may be deferred:
from app.cache_utils import invalidate_after_commit
with transaction.atomic():
user.nickname = "New"
user.save()
invalidate_after_commit(tournament, org_user, org_user.organization)
Direct invalidate_obj — safe only OUTSIDE transactions (e.g., after M2M .add()/.remove()):
from cacheops import invalidate_obj
org.admins.add(user) # M2M auto-commits
invalidate_obj(org) # Safe — data already committed
When to use which:
| Context | Use |
|---|---|
Inside transaction.atomic() |
invalidate_after_commit() |
Inside @transaction.atomic decorator |
invalidate_after_commit() |
Inside signal handlers (post_save, etc.) |
invalidate_after_commit() |
After .save() / M2M ops outside transactions |
Direct invalidate_obj() is safe |
After .update() / .bulk_create() |
invalidate_after_commit() (defensive) |
DTX Model Cache Dependencies
When modifying data, invalidate these related caches:
| Changed Model | Also Invalidate |
|---|---|
| DraftRound | Tournament, Draft, Team |
| Draft | Tournament |
| Team | Tournament (if tournament-scoped) |
| Game | Tournament, Team |
| CustomUser | Team (if member changes) |
Key Principles
- Invalidate on Write: Always invalidate related caches after mutations
- Use
invalidate_after_commit: Default to deferred invalidation in transactions — seeapp/cache_utils.py - Monitor Dependencies: Use
@cached_as(Model1, Model2, ...)to auto-invalidate - Use Specific Keys: Include request path or pk in cache keys
- Keep Fresh for Detail: Use
keep_fresh=Truefor single-object retrieval
Detailed References
- Cacheops Patterns - Decorator usage, cache keys
- Invalidation Strategies - When and how to invalidate
- Model Dependencies - DTX model relationships
Common Operations
Disable Cache for Management Commands
DISABLE_CACHE=true python manage.py <command>
Manual Cache Invalidation
from cacheops import invalidate_all, invalidate_model, invalidate_obj
# Nuclear option - invalidate everything
invalidate_all()
# Invalidate all instances of a model
invalidate_model(Tournament)
# Invalidate specific instance
invalidate_obj(tournament)
Check if Cache is Working
from django.core.cache import cache
cache.set('test_key', 'test_value', 30)
print(cache.get('test_key')) # Should print 'test_value'
Timeout Guidelines
| Data Type | Timeout | Reason |
|---|---|---|
| Static data | 60 * 60 (1h) | Rarely changes |
| Tournament state | 60 * 10 (10m) | Changes during events |
| Draft rounds | 60 * 10 (10m) | Active during drafts |
Discord guild members (discord_members_<guild_id>) |
60 * 60 (1h) | Admin-search-driven refreshes; daily avatar task reads from this same cache. See "Discord Member Cache" below. |
| Other external API short-burst caches | 15-60s | Per-request burst dedup only |
Discord Member Cache
Single Redis cache for guild members shared by two consumer patterns —
admin-driven and scheduled. Don't add a parallel cache for the same
data; extend the timeout or call refresh_discord_members instead.
Cache: discord_members_<guild_id> — full paginated member list
per guild, 1-hour TTL (constant: DISCORD_MEMBER_CACHE_TTL_S in
backend/discordbot/services/users.py).
Populated by:
discordbot.services.users.get_discord_members_data(guild_id)— on cache miss, paginates `GET /guilds
Установить django-redis-caching в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл django-redis-caching?
Django Redis caching with django-cacheops. This skill should be used when implementing caching, adding cache invalidation, optimizing API performance, modifying models that affect cached data, or debugging cache-related issues in the Django backend.
Как установить скилл django-redis-caching?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл django-redis-caching запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic