import json from functools import wraps from django_redis import get_redis_connection from django.db import models # Define a cache decorator _cache = get_redis_connection('default') def cache(func): @wraps(func) def wrapper(obj, *args): key = args[0] value = _cache.get(key) if value: return json.loads(value) result = func(obj, *args) _cache.set(key, json.dumps(result)) return result return wrapper
class User(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=5)
# Define a class method `get()` using the cache decorator. When data needs to be retrieved from the cache, simply call `get()` method @classmethod @cache def get(cls, id): # Query data from MySQL and save it to Redis result = cls.objects.get(id=id) return { 'id': result.id, 'name': result.name # If there is a date-time type data, it needs to be converted to string #'time': str(result.time) }