Python 将查询结果缓存到数据库

Python 将查询结果缓存到数据库,python,django,python-2.7,Python,Django,Python 2.7,呈现页面时,将执行对数据库的大量查询。我的任务是缓存在查询中获得的queryset,并在以后使用它。如果在下一次缓存查询期间,自上次初始化缓存已过5秒,则应删除旧缓存,并从数据库写入新数据 class BlacklistCache: CACHE_INITIAL_TIME = 0 def __init__(self): self._cache = None @property def cache(self): if time.ti

呈现页面时,将执行对数据库的大量查询。我的任务是缓存在查询中获得的queryset,并在以后使用它。如果在下一次缓存查询期间,自上次初始化缓存已过5秒,则应删除旧缓存,并从数据库写入新数据

class BlacklistCache:
    CACHE_INITIAL_TIME = 0

    def __init__(self):
        self._cache = None

    @property
    def cache(self):
        if time.time() - 5 > self.__class__.CACHE_INITIAL_TIME:
            self.__class__.CACHE_INITIAL_TIME = time.time()
            self._cache = None
        return self._cache

    @cache.setter
    def cache(self, value):
        self._cache = value


blacklist_cache = BlacklistCache()


def check_blacklist_cache(item_type):
    if blacklist_cache.cache:
        print('Exist')
        return blacklist_cache.cache
    else:
        print('New')
        blacklist = BlacklistedItem.objects.filter(item_type=item_type).values_list('item_id', flat=True)
        blacklist_cache.cache = blacklist
    return blacklist_cache.cache
但最后,第一次加载页面时,会打印
New
,并且在以后的所有加载中,都会打印
Exist
,并且不会覆盖缓存。我假设这个代码

if blacklist_cache.cache:
将从实例调用
get
方法,但它没有。 你能给我一些建议,或者可能是最有效的方法吗