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)

For example:

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.

Answers


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)

EDIT

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.

From:

https://docs.djangoproject.com/en/dev/topics/db/queries/#one-to-many-relationships

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.


Need Your Help

Draw object to screen using mouse listener java applet

java applet mouseevent

I am trying to create an applet that draws a christmas tree, then using buttons the user is able to draw decorations to the tree (a different button for each decoration).

Hide child divs in jquery

jquery html

So I have a string of Jquery stuff and I'm not sure why one part isn't working.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.