【问题标题】:Can not cache queryset in Django无法在 Django 中缓存查询集
【发布时间】:2015-12-02 16:07:56
【问题描述】:

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

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)

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

【问题讨论】:

    标签: django django-queryset django-cache


    【解决方案1】:

    我知道是什么原因造成的: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 无法识别 key timeout 参数并通过错误。这让我有些吃惊,因为 Debian 7 上的默认 redis 是 2.4。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 2014-01-31
      相关资源
      最近更新 更多