The Python Oracle

when exactly django query execution occures

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Cool Puzzler LoFi

--

Chapters
00:00 When Exactly Django Query Execution Occures
00:42 Accepted Answer Score 3
01:47 Thank you

--

Full question
https://stackoverflow.com/questions/6700...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django

#avk47



ACCEPTED ANSWER

Score 3


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