148 | | To order by a field in a different table, add the other table's name and a dot, |
149 | | like so:: |
| 148 | To order by a field in a different model, use the same syntax as when you are |
| 149 | querying across model relations. That is, the name of the field, followed by a |
| 150 | double underscore (``__``), followed by the name of the field in the new model, |
| 151 | and so on for as many models as you want to join. For example:: |
151 | | Entry.objects.order_by('blogs_blog.name', 'headline') |
| 153 | Entry.objects.order_by('blog__name', 'headline') |
| 154 | |
| 155 | If you try to order by a field that is a relation to another model, Django will |
| 156 | use the default ordering on the related model (or order by the related model's |
| 157 | primary key if there is no ``Meta.ordering`` specified. For example:: |
| 158 | |
| 159 | Entry.objects.order_by('blog') |
| 160 | |
| 161 | ...is identical to:: |
| 162 | |
| 163 | Entry.objects.order_by('blog__id') |
| 164 | |
| 165 | ...since the ``Blog`` model has no default ordering specified. |
| 166 | |
| 167 | Be cautious when ordering by fields in related models if you are also using |
| 168 | ``distinct()``. See the note in the `distinct()`_ section for an explanation |
| 169 | of how related model ordering can change the expected results. |
| 170 | |
| 171 | It is permissible to specify a multi-valued field to order the results by (for |
| 172 | example, a ``ManyToMany`` field). Normally this won't be a sensible thing to |
| 173 | do and it's really an advanced usage feature. However, if you know that your |
| 174 | queryset's filtering or available data implies that there will only be one |
| 175 | ordering piece of data for each of the main items you are selecting, the |
| 176 | ordering may well be exactly what you want to do. Use ordering on multi-valued |
| 177 | fields with care and make sure the results are what you expect. |
| 178 | |
| 179 | **New in Django development version:** If you don't want any ordering to be |
| 180 | applied to a query, not even the default ordering, call ``order_by()`` with no |
| 181 | parameters. |
| 182 | |
| 183 | **New in Django development version:** The syntax for ordering across related |
| 184 | models has changed. See the `Django 0.96 documentation`_ for the old behaviour. |
| 185 | |
| 186 | .. _Django 0.96 documentation: http://www.djangoproject.com/documentation/0.96/model-api/#floatfield |