Menu
CoddyTech

All and Get

Part of the Models and the Admin section of Coddy's Django journey. Lesson 8 of 23.

Before a page can show a book, your code has to read it back. Book.objects.all() returns a QuerySet, a list-like object you can loop over; each item is a Book with its fields as attributes. get() fetches exactly one row:

for book in Book.objects.all():
    print(book.author, book.year)

emma = Book.objects.get(title="Emma")
print(emma.year)   # 1815

get() expects one match. No match raises Book.DoesNotExist, several raise Book.MultipleObjectsReturned, and you catch them like any exception. Two books here are by Jane Austen:

try:
    Book.objects.get(author="Jane Austen")
except Book.MultipleObjectsReturned:
    print("More than one")

Left uncaught, the exception stops the script on that line.

challenge icon

Challenge

Easy

Rewrite explore.py:

  1. Print every book's title, one per line.
  2. Get Dune and print Dune costs and its price: Dune costs 9.99.
  3. Look up Ulysses, which is not on the shelf, and print Ulysses is not on the shelf instead of crashing.

Press Run. The Console lists the nine titles, then the two sentences.

Try it yourself

from books.models import Book

# 1. Print the title of every book, one per line.

# 2. Get Dune and print its price.

# 3. Look for Ulysses.
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