Does Django cache related ForeignKey and ManyToManyField fields once they're accessed?
Given the following model, does Django cache the related objects after the first time they're accessed?
class Post(models.Model): authors = models.ManyToManyField(User) category = models.ForeignKey(Category)
post = Post.objects.get(id=1) # as i understand this hits the database authors1 = post.authors.all() # does this his the database again? authors2 = post.authors.all() # as i understand this hits the database category1 = post.category # does this hit the database again? category2 = post.category
Note: currently working with Django 1.3, but it's good to know what's available in other versions.
In the first example the second query is cached. In the second case (I believe) they will both cause a DB hit unless you use select_related on the original query:
post = Post.objects.select_related('category').get(id=1)
I'm wrong about the second example. If you use select_related in the original query, you won't hit the database at all again (The ForeignKey is cached immediately). If you don't use select_related, you will hit the DB on the first query but the second query will be cached.
Forward access to one-to-many relationships is cached the first time the related object is accessed. Subsequent accesses to the foreign key on the same object instance are cached.
Note that the select_related() QuerySet method recursively prepopulates the cache of all one-to-many relationships ahead of time.