get_cache_or_query - Shortcut to common cache signature

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def get_cache_or_query(cache_key, model, seconds_to_cache=900, **kwargs):
    '''
        Based on concept by Rudy Menendez.
        Gets the query from cache or returns the orm.
        
        Example: the_game = get_cache_or_query('game1', Game,
                            seconds_to_cache=60*24*5, id=1) # 5 day timeout
    '''
    from django.core.cache import cache
    
    q = cache.get(cache_key)
    if not q:
        q = model.objects.get(**kwargs)
        cache.set(cache_key, q, seconds_to_cache)
    return q

More like this

  1. Run and cache only one instance of a heavy request by farnsworth 1 year, 5 months ago
  2. template + cache = crazy delicious by jacobian 4 years, 9 months ago
  3. Per-Instance On-Model M2M Caching by bryanhelmig 1 year, 6 months ago
  4. Prefill ForeignKey caches by insin 3 years, 4 months ago
  5. Ajax form with jQuery by Donn 3 years, 5 months ago

Comments

(Forgotten your password?)