Course Content
Django ORM Ninja: Advanced Techniques for Developers
Django ORM Ninja: Advanced Techniques for Developers
Lazy Queries
A QuerySet in Django is a collection of database queries to retrieve objects from your database. You've already seen QuerySets in the previous chapters; they behave quite similarly to list. And the information was displayed in the format we specified in the magic method __str__ in the mentioned models.
In Django's Object-Relational Mapping (ORM) system, queries are "lazy" by design. This means that a database query is not executed until the data is actually needed.
The actual database query is not executed at the time of creating the QuerySet. Instead, Django waits until the last possible moment to send the query to the database. This happens when you do something that requires the data.
In this example, the first line creates a QuerySet but does not immediately fetch data from the database. The data is only retrieved when the QuerySet is printed, demonstrating the lazy nature of Django's QuerySets.
This approach prevents unnecessary database hits. For example, if you create a QuerySet and then apply further filters to it, Django combines these into a single query, rather than executing multiple queries.
Thanks for your feedback!