Menu
CoddyTech

A List from the Database

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

The home page still lists three titles typed into the view. Pages and models meet in the view: it asks the ORM for rows and hands the QuerySet to the template, the way you passed a list before. A page of the books you have not read yet would be:

from django.shortcuts import render

from .models import Book


def to_read(request):
    books = Book.objects.filter(is_read=False)
    return render(request, "books/to_read.html", {"books": books})

The dot in from .models means this app's own folder. In the template, each item of the loop is a Book, so {{ book.title }} and {{ book.price }} read its fields, and {{ book }} alone prints its __str__.

challenge icon

Challenge

Easy
  • In books/views.py, give the template every book in the database as books, in place of the typed list.
  • In home.html, show each book as its title and year in brackets, like Dune (1965).

Press Run and open /. Add a book in the Shell tab, reload the page, and it is in the list.

Try it yourself

from django.shortcuts import render


def home(request):
    books = ["Dune", "Emma", "The Hobbit"]
    return render(request, "books/home.html", {"books": books})

All lessons in Models and the Admin

Practice on your own: Django playground