Menu
CoddyTech

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 rows

count() 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 icon

Challenge

Easy

Rewrite explore.py to print two lines:

  1. Science fiction: and how many science fiction books there are.
  2. Any Tolkien: and whether a book by J.R.R. Tolkien is 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Models and the Admin

Practice on your own: Django playground