class AppUser(models.Model):
user = models.ForeignKey(User, unique=True)
slug = models.SlugField(editable=False, blank=True)
For above model suppose we have a object "appuser" which we have rendered in templa开发者_如何转开发te
Does django hits User db each time when we use it like appuser.user.username in our code??
Any help on how in django/python db lookups are done while accessing foreign key and many-to-many variables ??
You should carefully read through this for all details to database access optimization: https://docs.djangoproject.com/en/1.3/topics/db/optimization/
And select_related()
:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related
As for a quick answer to your question: It depends on how you've retrieved the object
With
appuser = AppUser.objects.get(pk=id)
it will hit the database separately for appuser.user.
But with
appuser = AppUser.objects.select_related().get(pk=id)
It will do a joined query, so accessing appuser.user does not trigger an SQL query.
SQL Logging should be enabled if settings.DEBUG is set to True. As for your question, yes, this will AppUser will join with the User table(using the primary key) when you do a appuser.user.username.
If you are running the dev webserver, you should be able to see the logs on the console.
it's on the docs
querysets are lazy
when querysets are evaluated
to reduce db hits, check Béres Botond answer
精彩评论