The address object is indeed cached. You can see this if you print the contents of user.__dict__
before and after accessing user.address
. For example:
>>> user.__dict__
{'date_joined': datetime.datetime(2010, 4, 1, 12, 31, 59),
'email': u'[email protected]',
'first_name': u'myfirstname',
'id': 1L,
'is_active': 1,
'is_staff': 1,
'is_superuser': 1,
'last_login': datetime.datetime(2010, 4, 1, 12, 31, 59),
'last_name': u'mylastname',
'password': u'sha1$...$...',
'username': u'myusername'}
>>> country = user.address.country
>>> user.__dict__
{'_address': <myapp.models.address object at 0xwherever,
'email': u'[email protected]',
...etc}
So the user object gains a _address
object which is used for subsequent lookups on the related object.
You can use select_related()
when you first get the user to pre-populate this cache even before accessing address, so you only hit the database once.