How to Set Ordering in Django Model: Syntax and Examples
In Django, you set default ordering of model query results by adding an
ordering attribute inside the model's inner Meta class. This attribute is a list or tuple of field names, where prefixing a field with - orders it descending.Syntax
To set ordering in a Django model, define an inner Meta class and add the ordering attribute as a list or tuple of field names. Use a minus sign (-) before a field name to order descending.
- Meta: Inner class to hold model metadata.
- ordering: List or tuple of field names to order by.
- Field names: Strings matching model fields; prefix with
-for descending order.
python
class MyModel(models.Model): field1 = models.CharField(max_length=100) field2 = models.IntegerField() class Meta: ordering = ['field1', '-field2']
Example
This example shows a Book model ordered by title ascending and then by published_year descending. When you query Book.objects.all(), results come sorted automatically.
python
from django.db import models class Book(models.Model): title = models.CharField(max_length=200) published_year = models.IntegerField() class Meta: ordering = ['title', '-published_year'] # Usage example (in Django shell or view): # books = Book.objects.all() # for book in books: # print(book.title, book.published_year)
Output
Book objects returned ordered by title ascending, then published_year descending.
Common Pitfalls
Common mistakes when setting ordering include:
- Not using an inner
Metaclass. - Using a string instead of a list or tuple for
ordering. - Referencing fields that do not exist on the model.
- Expecting ordering to affect database schema or indexes (it only affects query results).
Always test your ordering by querying the model.
python
class WrongModel(models.Model): name = models.CharField(max_length=100) # Wrong: ordering as string instead of list or tuple class Meta: ordering = 'name' class CorrectModel(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ['name']
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Meta class | Defines model metadata including ordering | class Meta: ordering = ['field'] |
| Ordering list | List or tuple of fields to sort by | ordering = ['name', '-date'] |
| Descending order | Prefix field with '-' for descending | ordering = ['-created_at'] |
| Multiple fields | Order by first field, then second if tie | ordering = ['last_name', 'first_name'] |
Key Takeaways
Set default ordering in Django models inside the inner Meta class using the ordering attribute.
Use a list or tuple of field names; prefix with '-' for descending order.
Ordering affects query results, not database schema or indexes.
Always verify field names exist and ordering is a list or tuple, not a string.
Multiple fields can be combined to control sorting priority.