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) # 1815get() 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
EasyRewrite explore.py:
- Print every book's title, one per line.
- Get
Duneand printDune costsand its price:Dune costs 9.99. - Look up
Ulysses, which is not on the shelf, and printUlysses is not on the shelfinstead 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.
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