0 day streak
python / beginner
Snippet

Sorting Database Results

Use the order_by method to sort QuerySets. Prefixing a field name with a hyphen (-) sorts the results in descending order.

snippet.py
python
1
2
3
4
from .models import Article
# Get all articles sorted by date (newest first)
latest_articles = Article.objects.all().order_by('-published_date')
django
Breakdown
1
Article.objects.all()
Retrieves all records from the Article table.
2
.order_by('-published_date')
Sorts the retrieved objects by the date field in reverse chronological order.