when exactly django query execution occures

Viewed 82

In a technical interview a questioner asked me a weird question regarding to the execution of querysets. Suppose we have a profile model like below:

class Profile(models.Model):
    user = models.OneToOneField('User').select_related(User)
    surname = models.TextField(null=True)


q = Profile.object.all()
or 
q = Profile.object.get(id=1)

l = q.filter(active=True)

he asked how many query execution has been happened and I replied as the python interpreter executes Profile.object.all() at the begging then one query is already done. However, he answered zero, and one if we call the query, something like this:

for a in l:
   a.surname

Is his answer true in django?

another doubt was about models.OneToOneField('User'), why he didn't use django.contrib.auth.models.User and defined models.OneToOneField('User').select_related(User)

1 Answers

QuerySets are not evaluated until you do something that actually needs them to be evaluated. As the documentation for the class itself states a QuerySet:

Represent a lazy database lookup for a set of objects.

Emphasis on the word lazy. This is because one often needs to call or chain methods on a queryset, a good example being a group by requiring subsequent calls to .values() and .annotate(). If a queryset was evaluated directly then we would be making too many unneeded queries to the database, slowing down execution to a halt.

As to when exactly a queryset is evaluated I would list the answer in short (for the long answer refer to When QuerySets are evaluated [Django docs]):

  • Iterating a queryset
  • Slicing a queryset (with the step parameter)
  • Pickling/Caching a queryset
  • Calling repr(), len(), list(), or bool() on a queryset
  • Various methods like get(), first(), last(), latest(), or earliest(), etc. also make a query to the database
Related