I have a query which results only change once a day. Seems like a waste to be performing that query every request I get for that page. I am investigating using memcached for this.
How would I begin? Anyone have any suggestions or pitfalls I should avoid in using Django’s caching? Should I cache at the template or at the view?
This question might seem vague but it’s only because I’ve never dealt with caching before. So if there’s something I could elaborate on, please just ask.
Elaboration
Per Ken Cochrane:
-
How often does this data change: The relevant data would be locked in for that calendar date. So, for example, I’ll pull the data for 1/30/2011 and I’m okay with serving that cached copy for the whole day until 1/31/2011 where it would be refreshed.
-
Do I use this data in more then one place: Only in one view.
-
How much data is it going to be: An average of 10 model objects that contain about 15 fields with the largest being a
CharField(max_length=120). I will trim the number of fields down usingvalues()to about half of those.
Normally before I decide where to do the caching I ask myself a few questions.
Since I don’t know all of the details for your application, I’m going to make some assumptions.
With these assumptions you have 3 options.
1. cache the templates
2. cache the view
3. cache the queryset
Normally when I do my caching I cache the queryset, this allows me greater control of how I want to cache the data and I can reuse the same cached data in more then one place.
The easiest way that I have found to cache the queryset is to do this in the ModelManger for the model in question. I would create a method like get_calender_by_date(date) that will handle the query and caching for me. Here is a rough mockup
Some things to look out for when caching
When caching the template or view you need to watch out for the following
Hopefully that gives you enough information to get started. Good Luck.