I'm trying to find a way to cache the results of a query that won't change with frequency. For example, categories of products from an e-commerce (cellphones, TV, etc).
I'm thinking of using the template fragment caching, but in this fragment, I will iterate over a list of these categories. This list is avaliable in any part of the site, so it's in my base.html
file. Do I have always to send the list of categories when rendering the templates? Or is there a more dynamic way to do this, making the list always available in the template?
相关问题
- Django __str__ returned non-string (type NoneType)
- Django & Amazon SES SMTP. Cannot send email
- Django check user group permissions
- Django restrict pages to certain users
- UnicodeEncodeError with attach_file on EmailMessag
相关文章
- Profiling Django with PyCharm
- Why doesn't Django enforce my unique_together
- MultiValueDictKeyError in Django admin
- Django/Heroku: FATAL: too many connections for rol
- Is there a google API to read cached content? [clo
- Django is sooo slow? errno 32 broken pipe? dcramer
- Django: Replacement for the default ManyToMany Wid
- Upgrading transaction.commit_manually() to Django
Pop your cached query into Django's cache:
Then create a context processor to add the value of the cache to all templates:
Then add your context processor in your Django settings file:
Now you will be able to access the
cache
variable in all generic templates and all templates which have a requests context, which a template is given if this is done in the view:When to Set the Cache
It depends on what is contained in the cache. However a common problem is that Django only really gets to execute Python whenever a page request is sent, and this is often not where you want to do this kind of work.
An alternative is to create a custom management command for a particular app. You can then either run this manually when necessary, or more commonly set this to run as a cron job.
To create a management command you must create a class decended from
Command
inside of amanagement/commands
directory located inside of an app:The name of this file is important as this will be the name of the command. In this case you can now call this on the command line:
You can also use johnny-cache for automatic caching of querysets. It will (by default) cache all querysets, but you can force it not to cache some.