Django Order By

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()


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


You can just order by a field on the model:

class Author(models.Model):
    name = models.CharField()


Related Model

Order by a field on a related model:

class Book(models.Model):


If you just specify the related model without a specific field, like so:


It will either use the Meta info of Author, or default to the id field of the Author model.



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:


Case Sensitive

You can do the following to get case sensitive sorting:


No Ordering

And if you don’t want to have any ordering, not even the default ones, you can call it with no parameters:


Overriding Order By

Calling order_by a second time will clear the first order_by and leave the second:


Will just order by city

Written by Eddie Svirsky

Leave a Reply