8đź‘Ť
I’ve been doing a lot of reading since I posted this question yesterday and I’ll share what I’ve learned. These are my impressions of how you should approach caching based on what I’ve read, not on any experience I have. Therefore, I may get some things wrong.
First, you shouldn’t just turn caching on as a panacea for performance, especially if you don’t know what you’re doing. Caching adds more complexity to your stack, it creates another point of failure, and apparently it can sometimes cause weird problems that are difficult to troubleshoot. You’re probably better off not doing any caching until you’ve figured out how to measure your website’s performance, have done some profiling, and have in fact demonstrated that you have a performance problem. From what I’ve read, you’d be better off focusing on optimizing your database queries and minimizing your page weights before you try caching via Django. If you want to do any caching at all right off that bat, look at caching your images, stylesheets, and JavaScript via your web server (Apache, Nginx, etc.).
With respect to my question, I think I had the wrong notion of how caching works. When I enabled “per-site” caching in Django, what I think I said to Django was “store every response to every page request in your Redis cache until the cache fills up and starts evicting things.” If a page is requested and that page is still in the cache, the cache isn’t magically going to know whether or not that page has changed and then go fetch the updated version (if it has). It will continue returning that cached page no matter how many times I change it (unless it’s evicted).
What I did do just as a test was to apply the @never_cache decorator to the view in question. That fixed the problem I was having. However, as Lorenzo alluded to, apply caching on a case-by-case basis is probably a better approach. If you want to cache a particular view, use the @cache_page decorator. If you want to cache a portion of a template, use {% cache %}. Cache actual data that is expensive to compute via Django’s low-level API “django.core.cache.caches”. And if you want to do caching based on cache expiration and/or validation, use Django’s “Conditional View Processing” feature via the @condition decorator.
If you’re totally new to caching, I highly recommend that you read Mark Nottingham’s Caching Tutorial and Ryan Tomayko’s Things Caches Do.
I hope this helps!