Django CACHEOPS different timeout for different querysets

944 Views Asked by At

I'm using Django CACHEOPS. cacheops' README

In settings.py how can I config different timeouts for different querysets?

(cache the get queryset for 10 seconds and cache queryset fetches for 60 seconds)

Something like this: (This obviously has duplication key error)

CACHEOPS = {
    'blog.Article': {'ops': 'fetch', 'timeout': 60},
    'blog.Article': {'ops': 'get', 'timeout': 10},
}

My goal is: I want to cache each article detail page longer than the article list page.

1

There are 1 best solutions below

0
On

As you see a key in CACHEOPS definition is for models, not for queryset

blog.Article is a Article model in a blog application, not a queryset.

Then knowing the above you have only workarounds for a glitch in the cacheops and it would be

CACHEOPS_DEFAULTS = {
    'timeout': 60         # first level - a default
}

CACHEOPS = {
    'blog.*': {'ops': 'fetch', 'timeout': 60},  # second level - a default per application
    'blog.Article': {'ops': 'get', 'timeout': 10},
}

Rather use decorator to cover specific get on a specific model:

from cacheops import cached_as
@cached_as(Article, timeout=10)
def get_cached_article(...
     Article.objects. ... your queryset
     ...