Django order by lets you specify how your query results should be ordered. Here’s an example where we will order by the author’s name:
class Author(models.Model):
name = models.CharField()
Author.objects.order_by("name")
Django Query Order
If you don’t specify a specific order for a query, Django will look for a default Meta ordering for the model:
class Author(models.Model):
name = models.CharField()
class Meta:
ordering = ['name']
If Meta is not specified and you didn’t specify an order for the query, Django will just return the data in the order that the database returned it in, which most of the time means there is no specific order (not the same as random though).
Django Order By Options
Regular
You can just order by a field on the model:
class Author(models.Model):
name = models.CharField()
Author.objects.order_by('name')
Related Model
Order by a field on a related model:
class Book(models.Model):
models.ForeignKey('Author')
Book.objects.order_by('author__name')
If you just specify the related model without a specific field, like so:
Book.objects.order_by('author')
It will either use the Meta info of Author, or default to the id
field of the Author model.
Reverse
Author.objects.order_by('-name')
Multiple Fields
Order by multiple fields (meaning first by one then by the other):
Author.objects.order_by('-name', 'city')
Random Ordering
You can order by random
:
Author.objects.order_by('?')
Case Sensitive
You can do the following to get case sensitive sorting:
Author.objects.order_by(Lower('name'))
No Ordering
And if you don’t want to have any ordering, not even the default ones, you can call it with no parameters:
Author.objects.order_by()
Overriding Order By
Calling order_by a second time will clear the first order_by and leave the second:
Author.objects.order_by('name').order_by('city')
Will just order by city
Written by Eddie Svirsky