2

I read in the Django documentation that in principle Django queries are lazy, that is the database is not queried until absolutely necessary.

Now, as a matter of efficiency, when I retreive data via

FooModel.object.filter(...)

and I have defined a relationship between FooModel and BarModel, is the info from BarModel automatically retreived as well? Or does this only happen when I later reference any of the BarModel fields?

On a related note. I have been looking for a simple way to somehow just confirm this for myself by looking at logs or using a debugger but have not been able to. I'd be interested in tips on how to do this.

DisneylandSC
  • 926
  • 1
  • 5
  • 19

3 Answers3

3

BarModel is not automatically retrieved, also if you filter by BarModel field inside of object filter it would only join and use it as parameter.

If you are interested what query Django runs you could use something like following

foo = FooModel.object.filter(...)
print(foo.query) 

To get extra tables in django you should use select_related

iklinac
  • 14,944
  • 4
  • 28
  • 30
0

Django queries and joins are lazy, as mentioned. It means that in your case Django will not join with the child table unless the filter looks into the child table. It will also not retrieve data for the child object unless you access it from code.

You can verify this for your specific case with the MySQL general query log

Nir Levy
  • 4,613
  • 2
  • 34
  • 47
0

From the docs:

In general, the results of a QuerySet aren’t fetched from the database until you “ask” for them

So, until you explicitely ask for the results data (i.e., when iterating), you won't be hitting the database.

Using filter(..) means just adding clausules to the SQL query. For example, if you do filter(id=2), it'll just add WHERE id=2 in the SQL query.

RompePC
  • 815
  • 1
  • 8
  • 17