views:

41

answers:

1

The object user has a foreign key relationship to address. Is there a difference between samples 1 and 2? Does sample 1 run the query multiple times? Or is the address object cached?

# Sample 1
country = user.address.country
city = user.address.city
state = user.address.state

# Sample 2
address = user.address
country = address.country
city = address.city
state = address.state
+1  A: 

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.

Daniel Roseman