Reputation: 229361
Say I have the following models:
class Baz(models.Model):
winning = models.CharField(max_length=100)
class Bar(models.Model):
baz = models.ForeignKey(Baz)
class Foo(models.Model):
bar = models.ForeignKey(Bar)
Now I have an instance of Foo
, foo
. How many queries does the following line execute?
winning = foo.bar.baz.winning
Does it do one for each foreign-key .
, or is Django smart enough to only do one query here?
Upvotes: 1
Views: 208
Reputation: 1791
Here is the queries for winning = foo.bar.baz.winning
statement: (I'am not counting Foo.objects.. statemnt)
(0.000) SELECT "foo_bar"."id", "foo_bar"."baz_id" FROM "foo_bar" WHERE "foo_bar"."id" = 1 ; args=(1,)
(0.000) SELECT "foo_baz"."id", "foo_baz"."winning" FROM "foo_baz" WHERE "foo_baz"."id" = 1 ; args=(1,)
And here is my tip: add logging for django.db.backends in your settings. https://docs.djangoproject.com/en/dev/topics/logging/#django-db-backends
And you will see all your queries in your console. Or install Django debug toolbar as Francis suggesting you.
Upvotes: 1
Reputation: 118458
That will require 3 queries.
One to get foo, bar, and baz.
Use select_related()
to get them at once.
Foo.objects.get(id=1).select_related('bar__baz__winning')
Upvotes: 4
Reputation: 10919
There is a quick way to tell. Install Django Toolbar. Then check out the queries tab. It will give you all sorts of profiling info.
Though I believe +1 query per FK call
Upvotes: 2