| 517 | | To order by a field in a different table, add the other table's name and a dot, |
|---|
| 518 | | like so:: |
|---|
| 519 | | |
|---|
| 520 | | Entry.objects.order_by('blogs_blog.name', 'headline') |
|---|
| | 517 | To order by a field in a different model, use the same syntax as when you are |
|---|
| | 518 | querying across model relations. That is, the name of the field, followed by a |
|---|
| | 519 | double underscore (``__``), followed by the name of the field in the new model, |
|---|
| | 520 | and so on for as many models as you want to join. For example:: |
|---|
| | 521 | |
|---|
| | 522 | Entry.objects.order_by('blog__name', 'headline') |
|---|
| | 523 | |
|---|
| | 524 | If you try to order by a field that is a relation to another model, Django will |
|---|
| | 525 | use the default ordering on the related model (or order by the related model's |
|---|
| | 526 | primary key if there is no ``Meta.ordering`` specified. For example:: |
|---|
| | 527 | |
|---|
| | 528 | Entry.objects.order_by('blog') |
|---|
| | 529 | |
|---|
| | 530 | ...is identical to:: |
|---|
| | 531 | |
|---|
| | 532 | Entry.objects.order_by('blog__id') |
|---|
| | 533 | |
|---|
| | 534 | ...since the ``Blog`` model has no default ordering specified. |
|---|
| | 795 | |
|---|
| | 796 | ``order_by`` |
|---|
| | 797 | If you need to order the resulting queryset using some of the new fields |
|---|
| | 798 | or tables you have included via ``extra()`` use the ``order_by`` parameter |
|---|
| | 799 | to ``extra()`` and pass in a sequence of strings. These strings should |
|---|
| | 800 | either be model fields (as in the normal ``order_by()`` method on |
|---|
| | 801 | querysets), of the form ``table_name.column_name`` or an alias for a column |
|---|
| | 802 | that you specified in the ``select`` parameter to ``extra()``. |
|---|
| | 803 | |
|---|
| | 804 | For example:: |
|---|
| | 805 | |
|---|
| | 806 | q = Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"}) |
|---|
| | 807 | q = q.extra(order_by = ['-is_recent']) |
|---|
| | 808 | |
|---|
| | 809 | This would sort all the items for which ``is_recent`` is true to the front |
|---|
| | 810 | of the result set (``True`` sorts before ``False`` in a descending |
|---|
| | 811 | ordering). |
|---|
| | 812 | |
|---|
| | 813 | This shows, by the way, that you can make multiple calls to |
|---|
| | 814 | ``extra()`` and it will behave as you expect (adding new constraints each |
|---|
| | 815 | time). |
|---|