Django QuerySet Order By
Sorting database results in ascending or descending order
📊 What is order_by()?
The order_by() method sorts your QuerySet results by one or more fields. You can sort in ascending or descending order to organize data exactly how you need it.
# Order books by title
from myapp.models import Book
books = Book.objects.order_by('title')
print(books)
Output:
<QuerySet [<Book: Advanced Python>, <Book: Django Basics>, <Book: Python Guide>]>
Key order_by() Features
Ascending Order
Sort from lowest to highest
# A to Z, 0 to 9
books = Book.objects.order_by('price')
Descending Order
Sort from highest to lowest
# Z to A, 9 to 0
books = Book.objects.order_by('-price')
Multiple Fields
Sort by multiple criteria
# Sort by author, then price
books = Book.objects.order_by(
'author', 'price'
)
Random Order
Randomize results
# Random order
books = Book.objects.order_by('?')
🔹 Basic Ordering
Use order_by() to sort your QuerySet by any field. By default, sorting is in ascending order (A-Z, 0-9). This is useful for displaying data in a logical sequence.
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
price = models.DecimalField(max_digits=6, decimal_places=2)
published_date = models.DateField()
rating = models.FloatField()
# views.py
from myapp.models import Book
# Order by title (A to Z)
books = Book.objects.order_by('title')
# Order by price (lowest to highest)
books = Book.objects.order_by('price')
# Order by date (oldest to newest)
books = Book.objects.order_by('published_date')
for book in books:
print(f"{book.title} - ${book.price}")
Output:
Advanced Python - $45.00
Django Basics - $24.99
Python Guide - $29.99
🔹 Descending Order
Add a minus sign (-) before the field name to sort in descending order (Z-A, 9-0). This is perfect for showing newest items first or highest values at the top.
from myapp.models import Book
# Order by price (highest to lowest)
expensive_first = Book.objects.order_by('-price')
# Order by date (newest to oldest)
newest_first = Book.objects.order_by('-published_date')
# Order by rating (highest to lowest)
top_rated = Book.objects.order_by('-rating')
# Order by title (Z to A)
reverse_alpha = Book.objects.order_by('-title')
for book in expensive_first[:3]:
print(f"{book.title} - ${book.price}")
Output:
Web Development Pro - $59.99
Advanced Python - $45.00
Python Guide - $29.99
🔹 Multiple Field Ordering
Pass multiple field names to order_by() to create complex sorting. Django sorts by the first field, then uses subsequent fields as tiebreakers when values are equal.
from myapp.models import Book
# Order by author, then by price
books = Book.objects.order_by('author', 'price')
# Order by author (A-Z), then price (high to low)
books = Book.objects.order_by('author', '-price')
# Order by rating (high to low), then date (new to old)
books = Book.objects.order_by('-rating', '-published_date')
# Complex ordering
books = Book.objects.order_by('author', '-rating', 'title')
for book in books:
print(f"{book.author} - {book.title} (${book.price})")
Output:
Jane Smith - Advanced Python ($45.00)
Jane Smith - Python Basics ($19.99)
John Doe - Django Basics ($24.99)
John Doe - Python Guide ($29.99)
🔹 Combining with filter()
You can chain order_by() with filter() and other QuerySet methods to both filter and sort your results. The order of chaining doesn't matter for the final result.
from myapp.models import Book
# Filter then order
published_books = Book.objects.filter(
published=True
).order_by('-published_date')
# Order then filter (same result)
published_books = Book.objects.order_by(
'-published_date'
).filter(published=True)
# Complex query
affordable_top_rated = Book.objects.filter(
price__lt=50,
rating__gte=4.0
).order_by('-rating', 'price')
for book in affordable_top_rated:
print(f"{book.title} - Rating: {book.rating} - ${book.price}")
Output:
Python Guide - Rating: 4.8 - $29.99
Django Basics - Rating: 4.5 - $24.99
Advanced Python - Rating: 4.3 - $45.00
🔹 Random Ordering
Use order_by('?') to randomize your QuerySet results. This is useful for features like "random book of the day" or shuffling content displays.
from myapp.models import Book
# Get books in random order
random_books = Book.objects.order_by('?')
# Get 3 random books
random_three = Book.objects.order_by('?')[:3]
# Random published books
random_published = Book.objects.filter(
published=True
).order_by('?')
for book in random_three:
print(book.title)
Output:
Django Basics
Web Development Pro
Python Guide
🔹 Reversing Order
Use the reverse() method to flip the order of an already ordered QuerySet. This is more efficient than re-ordering with different parameters.
from myapp.models import Book
# Order by price ascending
books = Book.objects.order_by('price')
# Reverse to descending
books_reversed = books.reverse()
# Can also chain directly
books = Book.objects.order_by('title').reverse()
# Reverse complex ordering
books = Book.objects.order_by(
'author', 'price'
).reverse()
for book in books_reversed[:3]:
print(f"{book.title} - ${book.price}")
Output:
Web Development Pro - $59.99
Advanced Python - $45.00
Python Guide - $29.99