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
The address object is indeed cached. You can see this if you print the contents of
user.__dict__before and after accessinguser.address. For example:So the user object gains a
_addressobject 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.