Sorting Rows
Part of the Models and the Admin section of Coddy's Django journey. Lesson 11 of 23.
The cheapest book, the newest one, every title oldest first: each is a question about order. 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() skips the Book objects and returns the values of one field. Without flat=True each value comes in a one-item tuple, like ('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.
Press Run. The Console reads Cheapest: Pride and Prejudice and Titles by year: ['Pride and Prejudice', 'Emma', ...].
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