Sorting Rows
Part of the Models and the Admin section of Coddy's Django journey. Lesson 11 of 23.
Finding the cheapest book, the newest one, or every title from oldest to newest all mean sorting the books first. order_by() sorts one QuerySet by a field, as ordering in Meta does for all of them, and a minus sorts high to low. first() returns the first row, or None when there is none, so unlike get() it never raises:
Book.objects.order_by("-year").first() # <Book: SPQR by Mary Beard>
Book.objects.order_by("-price").values_list("author", flat=True)
# <QuerySet ['Mary Beard', 'Umberto Eco', ...]>values_list("author", flat=True) skips the Book objects and returns the values themselves: 'Mary Beard'. Without flat=True each value comes in a one-item tuple: ('Mary Beard',).
Challenge
MediumRewrite explore.py to print two lines:
Cheapest:and the title of the cheapest book.Titles by year:and a list of every title, oldest book first. Print the list itself.
Press Run: the Console reads Cheapest: Pride and Prejudice, then Titles by year: ['Pride and Prejudice', 'Emma', 'The Murder of Roger Ackroyd', 'The Hobbit', 'Foundation', 'Dune', 'The Name of the Rose', 'Neuromancer', 'SPQR'].
Try it yourself
from books.models import Book
# 1. Cheapest: the title of the cheapest book
# 2. Titles by year: every title, oldest book first, as a list
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