无法在Django中缓存查询集

时间:2015-12-02 16:07:56

标签: django django-queryset django-cache

在视图中,我有这个缓存,可以节省一些昂贵的查询:

from django.core.cache import cache
LIST_CACHE_TIMEOUT = 120
....

topics = cache.get('forum_topics_%s' % forum_id)        

if not topics:        
        topics = Topic.objects.select_related('creator') \
                            .filter(forum=forum_id).order_by("-created")
        print 'forum topics not in cache', forum_id #Always printed out
        cache.set('forum_topics_%s' % forum_id, topics, LIST_CACHE_TIMEOUT)

使用此方法缓存其他查询集结果时我没有问题,也无法想到这种奇怪行为的共鸣,所以我很感激您的提示。

1 个答案:

答案 0 :(得分:0)

我想出了导致这种情况的原因:memcache哈希值不能大于1mb。 所以我switched to redis,问题就消失了:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

重要提示:确保redis版本为2.6或higherredis-server --version 在旧版本的redis中,显然redis无法识别密钥超时参数和错误。这让我感到很沮丧,因为Debian 7上的默认redis是2.4。