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
EasyIn explore.py, above the print, add two books.
- With
create():Project Hail MarybyAndy Weir, year2021, price12.99, science fiction. Store the genre's value,scifi, not its label; take it from yourGenreclass. - By building a
Bookand callingsave():Klara and the SunbyKazuo Ishiguro, year2021, price11.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
2Querying with the ORM
Creating RowsAll and GetFilter and LookupsCounting RowsSorting RowsUpdate and DeletePractice on your own: Django playground