Most easiest ways to use caching is to use:
- per-site cache for the entire site.
- per-view cache for caching the output of individual views
But I'm more interested in mixing two other types of caching:
Trivial examples of them can be found at Caching websites with Django and Memcached…
But what if on the one hand we have some complex python code which give us a complex output (like dict, or list of dicts, or something like this) and on the other hand this complex output is used in the template for another complex work (e.g., building table with many dependencies).
How to deal with such cases?
Just use both of them
That is, complex output is cached in the python code and there is cached fragment in the template.Pros: simple enough
Cons: if the cache key used in the python code is expired, the complex calculation will be made in order to get the complex result. But the key used for template fragment might haven't expired, so the efforts are wasted.
Do the hard work, only if it's needed
Not only the key used in the python code should be checked, but also the one generated for the cached template fragment. If the last one is not expired, the hard work can be skipped.Pros: complex calculations are performed only when they are really needed
Cons: additional code is needed in order to generate same key as the one used by {% cache %} template tag. There is no guarantee that this key will be generated in the same way in the next Django version.
Cache only the final result
Save your template fragment that should be cached in separate template file. When you get your complex output form your hard calculations use render_to_string to get desire result and put it in the cache. The result is string, which can be used 'as is' in the template.I will be glad to hear your opinion on the topic.
No comments:
Post a Comment