We can create new book records and store them in our database, but we don’t have a way of seeing all the books that are in our database through our application. Let’s create a new feature in our application that can show us.
For this we will need both a new route and a corresponding template to display the data.
Uncomment this route in your app.py:
# Retrieve all books in descending order by submission time, and show a list view of them.
@app.route('/books')
def books():
# Query the database for all books, ordering by the book ID in descending order
all_books = Book.select().order_by(Book.id.desc())
# Using that data, render a page that shows the books in a list
return render_template('books.html', books=all_books)
We’ve seen a lot of this before - we’re creating a new route at “/books”, and we’re returning a template that contains the data about the books that we got from the database. The thing we haven’t seen before is the following line:
all_books = Book.select().order_by(Book.id.desc())
We can use our model to make queries on the database. To do this, we call .select() on the model. We can also chain other method calls to do additional things like order the list of what’s returned by certain criteria. When we store information in our database, an ID number is automatically assigned that begins at 1 and increments with each new record added. We’re asking it to sort by this ID number in descending order, so that new records will appear at the beginning of the list. We store the list of results returned from the database in a variable called “all_books”.
So we expect with this route that we’ll be able to see the list of books at /books.
Try it: http://localhost:3000/books
You get an error. What went wrong? Type into chat or unmute with what you think you need to do to resolve this issue.