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. Every model has Book.objects, its manager: its methods read and write the table. Django's ORM (object-relational mapper) turns those calls into SQL. 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 two books.

  • With create(): Project Hail Mary by Andy Weir, year 2021, price 12.99, science fiction. Store the genre's value, scifi, not its label; take it from your Genre class.
  • By building a Book and calling save(): Klara and the Sun by Kazuo Ishiguro, year 2021, price 11.50.

Press Run: the Console reads 11 books on the shelf.

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