What is the default order of a list returned from a Django filter call?

There is NO DEFAULT ORDER, a point that can not be emphasized enough because everyone does it wrong.

A table in a database is not an ordinary html table, it is an unordered set of tuples. It often surprises programmers only used to MySQL because in that particular database the order of the rows are often predictable due to it not taking advantage of some advanced optimization techniques. For example, it is not possible to know which rows will be returned, or their order in any of the following queries:

select * from table limit 10
select * from table limit 10 offset 10
select * from table order by x limit 10

In the last query, the order is only predictable if all values in column x are unique. The RDBMS is free to returns any rows in any order it pleases as long as it satisfies the conditions of the select statement.

Though you may add a default ordering on the Django level, which causes it to add an order by clause to every non-ordered query:

class Table(models.Model):
    ...
    class Meta:
        ordering = ['name']

Note that it may be a performance drag, if for some reason you don’t need ordered rows.

Leave a Comment