Options.ordering
The default ordering for the object, for use when obtaining lists of objects:
1 | ordering = [ '-order_date' ] |
This is a tuple or list of strings. Each string is a field name with an optional “-” prefix, which indicates descending order. Fields without a leading “-” will be ordered ascending. Use the string ”?” to order randomly.
For example, to order by a pub_date
field ascending, use this:
1 | ordering = [ 'pub_date' ] |
To order by pub_date
descending, use this:
1 | ordering = [ '-pub_date' ] |
To order by pub_date
descending, then by author
ascending, use this:
1 | ordering = [ '-pub_date' , 'author' ] |
Default ordering also affects aggregation queries.
Warning
Ordering is not a free operation. Each field you add to the ordering incurs a cost to your database. Each foreign key you add will implicitly include all of its default orderings as well.
If a query doesn’t have an ordering specified, results are returned from the database in an unspecified order. A particular ordering is guaranteed only when ordering by a set of fields that uniquely identify each object in the results. For example, if a name
field isn’t unique, ordering by it won’t guarantee objects with the same name always appear in the same order.
Please login to continue.