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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.