1 """ |
|
2 6. Specifying ordering |
|
3 |
|
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. |
|
7 |
|
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. |
|
11 |
|
12 The ordering attribute is not required. If you leave it off, ordering will be |
|
13 undefined -- not random, just undefined. |
|
14 """ |
|
15 |
|
16 from django.db import models |
|
17 |
|
18 class Article(models.Model): |
|
19 headline = models.CharField(maxlength=100) |
|
20 pub_date = models.DateTimeField() |
|
21 class Meta: |
|
22 ordering = ('-pub_date', 'headline') |
|
23 |
|
24 def __str__(self): |
|
25 return self.headline |
|
26 |
|
27 __test__ = {'API_TESTS':""" |
|
28 # Create a couple of Articles. |
|
29 >>> from datetime import datetime |
|
30 >>> a1 = Article(headline='Article 1', pub_date=datetime(2005, 7, 26)) |
|
31 >>> a1.save() |
|
32 >>> a2 = Article(headline='Article 2', pub_date=datetime(2005, 7, 27)) |
|
33 >>> a2.save() |
|
34 >>> a3 = Article(headline='Article 3', pub_date=datetime(2005, 7, 27)) |
|
35 >>> a3.save() |
|
36 >>> a4 = Article(headline='Article 4', pub_date=datetime(2005, 7, 28)) |
|
37 >>> a4.save() |
|
38 |
|
39 # By default, Article.objects.all() orders by pub_date descending, then |
|
40 # headline ascending. |
|
41 >>> Article.objects.all() |
|
42 [<Article: Article 4>, <Article: Article 2>, <Article: Article 3>, <Article: Article 1>] |
|
43 |
|
44 # Override ordering with order_by, which is in the same format as the ordering |
|
45 # attribute in models. |
|
46 >>> Article.objects.order_by('headline') |
|
47 [<Article: Article 1>, <Article: Article 2>, <Article: Article 3>, <Article: Article 4>] |
|
48 >>> Article.objects.order_by('pub_date', '-headline') |
|
49 [<Article: Article 1>, <Article: Article 3>, <Article: Article 2>, <Article: Article 4>] |
|
50 |
|
51 # Use the 'stop' part of slicing notation to limit the results. |
|
52 >>> Article.objects.order_by('headline')[:2] |
|
53 [<Article: Article 1>, <Article: Article 2>] |
|
54 |
|
55 # Use the 'stop' and 'start' parts of slicing notation to offset the result list. |
|
56 >>> Article.objects.order_by('headline')[1:3] |
|
57 [<Article: Article 2>, <Article: Article 3>] |
|
58 |
|
59 # Getting a single item should work too: |
|
60 >>> Article.objects.all()[0] |
|
61 <Article: Article 4> |
|
62 |
|
63 # Use '?' to order randomly. (We're using [...] in the output to indicate we |
|
64 # don't know what order the output will be in. |
|
65 >>> Article.objects.order_by('?') |
|
66 [...] |
|
67 """} |
|