Counting Rows
Part of the Models and the Admin section of Coddy's Django journey. Lesson 10 of 23.
To say how many science fiction books you own, you could load them all and count in Python. The database counts faster. Each of these runs one small query and gets back a single answer:
Book.objects.filter(is_read=True).count() # 1
Book.objects.filter(price__gt=20).exists() # False
len(Book.objects.all()) # 9, after loading all 9 rowscount() returns how many rows match. exists() answers True or False: is there at least one? Both go at the end of a QuerySet, after filter() or exclude(). len() gives the same number as count(), but only after every row has come into Python, which is slow on a big table.
Challenge
EasyRewrite explore.py to print two lines:
Science fiction:and how many science fiction books there are.Any Tolkien:and whether a book byJ.R.R. Tolkienis on the shelf.
Press Run. The Console reads Science fiction: 3 and Any Tolkien: True.
Try it yourself
from books.models import Book
# 1. Science fiction: how many science fiction books there are
# 2. Any Tolkien: whether a book by J.R.R. Tolkien is on the shelf
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Models and the Admin
2Querying with the ORM
Creating RowsAll and GetFilter and LookupsCounting RowsSorting RowsUpdate and DeletePractice on your own: Django playground