[Django]-When does django run the query for a OneToOneField?

3👍

It doesn’t look like Django runs the query until you call the relation

class Bar(models.Model):
    name = models.CharField(max_length=20)

class Foo(models.Model):
    bar = models.OneToOneField(Bar)

in shell:

In [1]: Bar.objects.create(name='chocolate')
Out[1]: <Bar: Bar object>
In [2]: Foo.objects.create(bar=Out[1])
Out[2]: <Foo: Foo object>
In [3]: from django.db import connection
In [4]: connection.queries
Out[4]:
[{u'sql': u"QUERY = u'BEGIN' - PARAMS = ()", u'time': u'0.000'},
 {u'sql': u'QUERY = u\'INSERT INTO "myapp_bar" ("name") VALUES (%s)\' - PARAMS = (u\'chochalate\',)',
  u'time': u'0.001'},
 {u'sql': u"QUERY = u'BEGIN' - PARAMS = ()", u'time': u'0.000'},
 {u'sql': u'QUERY = u\'INSERT INTO "myapp_foo" ("bar_id") VALUES (%s)\' - PARAMS = (1,)',
  u'time': u'0.001'}]
In [5]: foo = Foo.objects.all()
In [6]: foo
Out[6]: [<Foo: Foo object>]
In [7]: connection.queries
Out[7]:
[
 # ... same as above ...
 {u'sql': u'QUERY = u\'SELECT "myapp_foo"."id", "myapp_foo"."bar_id" FROM "myapp_foo" LIMIT 21\' - PARAMS = ()',
  u'time': u'0.000'}] # bar is not queried 
In [8]: foo.bar
Out[8]: <Bar: Bar object>

In [9]: connection.queries
Out[9]:
[
 # ... same as above ...
 {u'sql': u'QUERY = u\'SELECT "myapp_bar"."id", "myapp_bar"."name" FROM "myapp_bar" WHERE "myapp_bar"."id" = %s LIMIT 21\' - PARAMS = (1,)',
  u'time': u'0.000'}] # now bar is queried 
👤Ben

Leave a comment