python - How to cache query result in django? -



python - How to cache query result in django? -

i trying cache query results on django app. however, seems caching whole app. tried next logi:

def cacheview(): result = cache.get('key') if result none: result = model.objects.get(id=1) cache.set('key', 'result')

i calling method when user logs in. however, if seek logout after login, keeps me on same page if still logged in. tried follow django documentation on cache @ http://docs.djangoproject.com/en/1.2/topics/cache/ no success.

another thing tried if seek utilize cache decorator above view as:

@cache_control(max_age=1000) def cacheview(): ...

it gives error saying "response header not defined". new django , sure missed something. idea?

rtfm :) official django docs: caching , querysets

each queryset contains cache, minimize database access. (...)

and:

in newly created queryset, cache empty. first time queryset evaluated -- and, hence, database query happens -- django saves query results in queryset's cache , returns results have been explicitly requested (e.g., next element, if queryset beingness iterated over). subsequent evaluations of queryset reuse cached results.

caching done automagically in case of querysets (results of queries).

edit: code pasted in question. if key doesn't exist in cache have create add() method remember expire default after 30sec. if want kept longer have add together timeout alternative add()/set() method.

if want cache whole site (to ie. decorators used them), need add together proper middleware middleware_classes in settings.py (in exact order, because middleware order matters, loaded 1 1 define them):

middleware_classes = ( # ... 'django.middleware.cache.updatecachemiddleware', 'django.middleware.common.commonmiddleware', 'django.middleware.cache.fetchfromcachemiddleware', # ... )

if don't have them, you'll receiving bad header errors every time you'll utilize caching-per-site capabilities.

python django memcached

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -