0

For instance:

e = Entries.objects.filter(blog__name='Something')

Does this cache blog as well or should I still add select_related('blog') to this.

Azsgy
  • 3,139
  • 2
  • 29
  • 40
Utumbu
  • 432
  • 3
  • 7
  • 18
  • Related: https://stackoverflow.com/questions/33230540/django-select-related-when-to-use-it#33230991 – dfundako Apr 05 '18 at 20:42
  • Well, when you run that code and then examine the attributes of e, do you see attributes from blog or just entries? – dfundako Apr 05 '18 at 20:43

2 Answers2

0

The filter(blog__name='Something') means that Django will do a join when it fetches the queryset. However if you want to access the related blogs you still have to use select_related.

You might find django-debug-toolbar useful so that you can check the queries yourself.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
0

You will see attributes of everything blog and anything farther down as well. Django automagically takes care of it all. But it will do additional queries internally as needed to get blog (beyond blog_id) and anything else. Use select_related to get anything you know you will use. If select_related doesn't work then most of the time prefetch_related will work instead. The difference is that prefetch_related does an extra query for each table. That is still better than letting Django do everything automagically if the query includes more than one record of the main table - i.e., 1 + 1 instead of 1 + n.

I suspect part of the confusion is about filter(). filter and exclude and other ways of getting anything less than all() will reference the other tables in the WHERE part of the query but Django doesn't retrieve fields from those tables unless/until you access them, unless you use select_related or prefetch_related.