Querying with objects.all()
In this page:
Fetching Every Row
Model.objects.all() returns a QuerySet representing every row in that model's table, in the order the database returns them (or Meta.ordering if set).
Example: Fetching Every Row
Model.objects.all() returns a QuerySet representing every row in that model's table, in the order the database returns them (or Meta.ordering if set).
books = Book.objects.all()
for book in books:
print(book.title)
⚠️ Run this command in your terminal.
QuerySets Are Lazy
Calling .all() doesn't hit the database right away. Django only runs the actual SQL query the moment you iterate over the QuerySet, print it, or convert it to a list.
Note: This laziness lets you keep chaining filters before the query actually executes.
Example: QuerySets Are Lazy
Calling .all() doesn't hit the database right away. Django only runs the actual SQL query the moment you iterate over the QuerySet, print it, or convert it to a list.
qs = Book.objects.all()
print('query not run yet')
for book in qs:
print(book.title)
⚠️ Run this command in your terminal.
Counting Results
Calling .count() on a QuerySet asks the database to count rows directly, which is faster than fetching every row just to measure len().
Example: Counting Results
Calling .count() on a QuerySet asks the database to count rows directly, which is faster than fetching every row just to measure len().
total = Book.objects.all().count()
print(total)
⚠️ Run this command in your terminal.
- Calling list(Model.objects.all()) unnecessarily, forgetting that a QuerySet is already iterable on its own.
- Assuming Model.objects.all() returns the results immediately, when it's actually lazy and only hits the database once you iterate or evaluate it.
- Looping over a large objects.all() result just to filter it in Python, instead of filtering in the database with .filter().
- Model.objects.all() returns a QuerySet containing every row currently in that model's table.
- QuerySets are lazy — the database query only runs when the results are actually used.
- You can loop over a QuerySet directly with a for loop, just like a list.
- objects is the default manager Django attaches to every model automatically.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: