Index: query.py
===================================================================
--- query.py	(revision 3739)
+++ query.py	(working copy)
@@ -446,6 +446,33 @@
         where.extend(where2)
         params.extend(params2)
 
+        # Resolve order_by dependencies before joins to order by related tables
+        order_by = []
+        if self._order_by is not None: # use order_by = () to disable ordering
+            ordering_to_use = self._order_by
+        else:
+            ordering_to_use = opts.ordering
+        
+        for f in handle_legacy_orderlist(ordering_to_use):
+            if "." in f: # dot-style field, fall back to old ordering code below
+                order_by = []
+                break
+            elif f == '?': # Special case.
+                order_by.append(backend.get_random_function_sql())
+            elif f.startswith('-'):
+                path = f[1:].split(LOOKUP_SEPARATOR)
+                order = "DESC"
+            else:
+                path = f.split(LOOKUP_SEPARATOR)
+                order = "ASC"
+
+            joins3, where3, params3 = lookup_inner(path, 'exact', False, opts, opts.db_table, None)
+            joins.update(joins3)
+
+            # hack to get fieldname to order by. modify lookup_inner to supply this instead.
+            field = where3[0].replace(' = %s', '')
+            order_by.append('%s %s' % (field, order))
+
         # Add additional tables and WHERE clauses based on select_related.
         if self._select_related:
             fill_table_cache(opts, select, tables, where, opts.db_table, [opts.db_table])
@@ -471,11 +498,12 @@
             sql.append(where and "WHERE " + " AND ".join(where))
 
         # ORDER BY clause
-        order_by = []
         if self._order_by is not None:
             ordering_to_use = self._order_by
         else:
             ordering_to_use = opts.ordering
+        if order_by: # dont try to set up ordering again if already done
+            ordering_to_use = []
         for f in handle_legacy_orderlist(ordering_to_use):
             if f == '?': # Special case.
                 order_by.append(backend.get_random_function_sql())
