无法在 Django 中缓存查询集

Can not cache queryset in Django

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

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)

我使用这种方法缓存其他查询集结果没有问题,也想不出这种奇怪行为的原因,所以我很感谢你的提示。

我弄清楚是什么原因造成的: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。