djangocachingdjango-cache

How to use the cached results in cacheops with django


I am trying to use cacheops where I have a view that contains a variable I want to cache

bo = Bo.objects.all().cache()

The chached bo I tried to use in another view like this

all = cache.get('bo')

This does not work Here is the traceback

....
  File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\cacheops\simple.py", line 83, in get
    return self._get(get_prefix() + cache_key)
  File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\cacheops\simple.py", line 99, in _get
    raise CacheMiss
cacheops.simple.CacheMiss

My settings.py

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

CACHEOPS_DEGRADE_ON_FAILURE=True
CACHEOPS_ENABLED = True
CACHEOPS_REDIS = {
    'host': 'localhost',
    'port': 6379,}
CACHEOPS = {
    'libman.*': {'ops': 'all', 'timeout': 60*15},}

Solution

  • I was able to solve it by putting it in a try except block

    try:
        bo = cache.get('bo')
    except CacheMiss:
        bo = Bo.objects.all().cache()
        cache.set('bo',bo)