4
Specify default ordering for a model using the ``ordering`` attribute, which
5
should be a list or tuple of field names. This tells Django how to order the
6
results of ``get_list()`` and other similar functions.
8
If a field name in ``ordering`` starts with a hyphen, that field will be
9
ordered in descending order. Otherwise, it'll be ordered in ascending order.
10
The special-case field name ``"?"`` specifies random order.
12
The ordering attribute is not required. If you leave it off, ordering will be
13
undefined -- not random, just undefined.
16
from django.core import meta
18
class Article(meta.Model):
19
headline = meta.CharField(maxlength=100)
20
pub_date = meta.DateTimeField()
22
ordering = ('-pub_date', 'headline')
28
# Create a couple of Articles.
29
>>> from datetime import datetime
30
>>> a1 = articles.Article(headline='Article 1', pub_date=datetime(2005, 7, 26))
32
>>> a2 = articles.Article(headline='Article 2', pub_date=datetime(2005, 7, 27))
34
>>> a3 = articles.Article(headline='Article 3', pub_date=datetime(2005, 7, 27))
36
>>> a4 = articles.Article(headline='Article 4', pub_date=datetime(2005, 7, 28))
39
# By default, articles.get_list() orders by pub_date descending, then
41
>>> articles.get_list()
42
[Article 4, Article 2, Article 3, Article 1]
44
# Override ordering with order_by, which is in the same format as the ordering
45
# attribute in models.
46
>>> articles.get_list(order_by=['headline'])
47
[Article 1, Article 2, Article 3, Article 4]
48
>>> articles.get_list(order_by=['pub_date', '-headline'])
49
[Article 1, Article 3, Article 2, Article 4]
51
# Use the "limit" parameter to limit the results.
52
>>> articles.get_list(order_by=['headline'], limit=2)
53
[Article 1, Article 2]
55
# Use the "offset" parameter with "limit" to offset the result list.
56
>>> articles.get_list(order_by=['headline'], offset=1, limit=2)
57
[Article 2, Article 3]
59
# Use '?' to order randomly. (We're using [...] in the output to indicate we
60
# don't know what order the output will be in.
61
>>> articles.get_list(order_by=['?'])