285 | | # Calculate lookup_order_field. |
286 | | # If the order-by field is a field with a relationship, order by the |
287 | | # value in the related table. |
288 | | lookup_order_field = self.order_field |
289 | | order_type = self.order_type == 'desc' and '-' or '' |
290 | | try: |
291 | | f = self.lookup_opts.get_field(self.order_field, many_to_many=False) |
292 | | except models.FieldDoesNotExist: |
293 | | pass |
294 | | else: |
295 | | if isinstance(f.rel, models.OneToOneRel): |
296 | | # For OneToOneFields, don't try to order by the related object's ordering criteria. |
297 | | pass |
298 | | elif isinstance(f.rel, models.ManyToOneRel): |
299 | | rel_ordering = f.rel.to._meta.ordering and f.rel.to._meta.ordering[0] or f.rel.to._meta.pk.column |
300 | | if rel_ordering[0] == '-': |
301 | | rel_ordering = rel_ordering[1:] |
302 | | order_type = not order_type and '-' or '' |
303 | | lookup_order_field = '%s.%s' % (f.rel.to._meta.db_table, rel_ordering) |
304 | | # FIXME: Must use select_related() becuase the lookup field may |
305 | | # be in a table not otherwise referenced yet. |
306 | | qs = qs.select_related() |
307 | | |