Consider the following Django model:
class Name(models.Model):
pkid = models.BigAutoField(primary_key=True)
person = models.ForeignKey(to=Person,
on_delete=models.CASCADE)
full_name = models.CharField(max_length=100)
Will the following query automatically also do a join and retrieve the connected Person
object, too?
results = models.Name.objects.all()
Or are all foreign key reference fields in Django automatically deferred until they are accessed?
print(results[0].person)
CodePudding user response:
Django does not by default query foreign models when retrieving an instance, however this can bet configured using the select_related
method. Instead, the foreign instances are queried when referenced (e.g. when results[0].person
is evaluated).
If you want to explore how Django queries the database, you can view django.db.connection.queries
(as explained in How to see the raw SQL queries Django is running?).
For example:
First import:
from django.db import connection
Default functionality:
print("queries: ", len(connection.queries)) # 0
results = models.Name.objects.all()
print("queries: ", len(connection.queries)) # 1
print(results[0].person)
print("queries: ", len(connection.queries)) # 2
With select_related
:
print("queries: ", len(connection.queries)) # 0
results = models.Name.objects.select_related("person").all()
print("queries: ", len(connection.queries)) # 1
print(results[0].person)
print("queries: ", len(connection.queries)) # 1