How to Use order_by in Django: Syntax and Examples
In Django, use the
order_by() method on a queryset to sort results by one or more model fields. Prefix a field name with - to sort in descending order; otherwise, sorting is ascending by default.Syntax
The order_by() method takes one or more field names as arguments to sort the queryset. Use a field name to sort ascending, or prefix it with - to sort descending.
- order_by('field'): Sort ascending by
field. - order_by('-field'): Sort descending by
field. - order_by('field1', '-field2'): Sort ascending by
field1, then descending byfield2.
python
queryset.order_by('field') queryset.order_by('-field') queryset.order_by('field1', '-field2')
Example
This example shows how to order a list of books by their published_date ascending, and then by title descending.
python
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) published_date = models.DateField() # Query to get books ordered by published_date ascending, title descending books = Book.objects.order_by('published_date', '-title') for book in books: print(f"{book.published_date} - {book.title}")
Output
2020-01-01 - Zebra Tales
2020-01-01 - Alpha Story
2021-05-15 - Brave New World
2022-07-20 - Coding Fun
Common Pitfalls
Common mistakes when using order_by() include:
- Forgetting the
-prefix for descending order. - Using field names that do not exist on the model, causing errors.
- Calling
order_by()multiple times on the same queryset, which overrides previous ordering.
Always check your field names and use order_by() once with all desired fields.
python
wrong = Book.objects.order_by('title') wrong = wrong.order_by('-published_date') # Overrides previous order right = Book.objects.order_by('title', '-published_date') # Correct combined ordering
Quick Reference
| Usage | Description |
|---|---|
| order_by('field') | Sort ascending by field |
| order_by('-field') | Sort descending by field |
| order_by('field1', '-field2') | Sort ascending by field1, then descending by field2 |
| order_by() | Remove any ordering, return unordered queryset |
Key Takeaways
Use order_by() on querysets to sort results by one or more fields.
Prefix field names with '-' to sort in descending order.
Multiple calls to order_by() override previous ordering; combine fields in one call.
Ensure field names exist on the model to avoid errors.
Use order_by() with no arguments to clear ordering.