[Django]-Django – Optimize queries with select_related()

6👍

First, all the occurrences of .all() in your examples can be deleted; the manager (.objects) already has almost all methods of the QuerySet, except for .delete().

.select_related is only helpful when your eventual query returns model instances; then, all the foreign key of each instance will be pre-loaded.

But if you are using .values you are getting dictionaries, and there are no foreign key attributes to pre-load. So it should not be used in that case.

When you do .values('owner__name') Django already sees that it needs to join owners and cars, no extra queries are done.

In the last one you want Countries, so use Country.objects:

Country.objects.filter(driver__car__isnull=False).values('name')

Leave a comment