Menu
CoddyTech

Creating Rows

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

Your shelf needs new books, and you will never write SQL, the language databases speak: Django's ORM turns Python calls into SQL. Every model has a manager, Book.objects, your way into its table. In this chapter you write ORM code in explore.py. Run adds nine books, then runs the file the way python manage.py shell < explore.py would, and what it prints shows in the Console.

Book.objects.create(title="Beloved", author="Toni Morrison", year=1987, price="13.00")

create() builds a row and saves it in one step; a field you leave out takes its default. The same in two steps, with a change in between:

silmarillion = Book(title="The Silmarillion", author="J.R.R. Tolkien", year=1977, price="10.50")
silmarillion.is_read = True
silmarillion.save()

Until save() runs, the object lives only in Python and its id is None.

challenge icon

Challenge

Easy

In explore.py, above the print:

  • Add Project Hail Mary by Andy Weir, 2021, 12.99, science fiction, in one step.
  • Add Klara and the Sun by Kazuo Ishiguro, 2021, 11.50, by building a Book and saving it.

Press Run. The Console reads 11 books on the shelf, and the Data tab lists the two new rows.

Try it yourself

from books.models import Book

# Add the two books here.


print(Book.objects.count(), "books on the shelf")

All lessons in Models and the Admin

Practice on your own: Django playground