Werda
Werda

Reputation: 279

Django - expire django template cache based on variables

Its not to hard to invalidate a particular template cache in django

def invalidate_cache_key(fragment_name, *variables):
   args = md5_constructor(u':'.join([urlquote(var) for var in variables]))
   cache_key = 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
   cache.delete(cache_key)

However I have a situation where I need to delete all cached fragments that have had a certain variable passed to them. For example, delete all cached fragments about the car brand 'Toyota'.

{% cache 100000 car_content car.brand %}

Essentially is there a way to get all cache_keys based on a certain set of criteria? I have thought dangerously about changing the cache source but I was wondering if there might be a better solution to this problem.

Upvotes: 5

Views: 1074

Answers (2)

Tyler
Tyler

Reputation: 6881

I do this with caching namespaces. Here is a decent explanation:

http://blog.dberg.org/2008/07/user-based-memcached-namespaces.html

Upvotes: 1

webjunkie
webjunkie

Reputation: 7039

Use a date in the cache key:

{% cache 100000 car_content car.brand car.brand.last_modified %}

That way all fragments are created each time the brand gets modified.

Upvotes: 0

Related Questions