Update and Delete
Part of the Models and the Admin section of Coddy's Django journey. Lesson 12 of 23.
Prices change and books leave the shelf. To change one book, set its attribute and call save(); without save() the table keeps the old value. To change many rows at once, call update() on a QuerySet. It runs one UPDATE and returns how many rows changed. delete() works the same way and returns how many rows went, in all and per model:
Book.objects.filter(year__lt=1900).update(price="5.00") # 2
Book.objects.filter(price__gt=14).delete() # (1, {'books.Book': 1})Both act on exactly the rows of the QuerySet, so filter first. Book.objects.update(is_read=True) marks every book, and neither method asks before it acts.
Challenge
EasyIn explore.py, above the last print:
Duneis on sale: set its price to7.99.- Mark every book by
Jane Austenas read, in one query. - Delete every mystery book, in one query.
Press Run. The Console reads 7 books on the shelf, and the Data tab shows Dune at 7.99 and no mysteries.
Try it yourself
from books.models import Book
# 1. Dune is on sale: set its price to 7.99.
# 2. Mark every book by Jane Austen as read.
# 3. Give away every mystery book.
print(Book.objects.count(), "books on the shelf")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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