Ticket #2210: order_by_related.diff

File order_by_related.diff, 2.1 KB (added by serbaut@…, 18 years ago)

Patch for order_by related fields

  • query.py

     
    446446        where.extend(where2)
    447447        params.extend(params2)
    448448
     449        # Resolve order_by dependencies before joins to order by related tables
     450        order_by = []
     451        if self._order_by is not None: # use order_by = () to disable ordering
     452            ordering_to_use = self._order_by
     453        else:
     454            ordering_to_use = opts.ordering
     455       
     456        for f in handle_legacy_orderlist(ordering_to_use):
     457            if "." in f: # dot-style field, fall back to old ordering code below
     458                order_by = []
     459                break
     460            elif f == '?': # Special case.
     461                order_by.append(backend.get_random_function_sql())
     462            elif f.startswith('-'):
     463                path = f[1:].split(LOOKUP_SEPARATOR)
     464                order = "DESC"
     465            else:
     466                path = f.split(LOOKUP_SEPARATOR)
     467                order = "ASC"
     468
     469            joins3, where3, params3 = lookup_inner(path, 'exact', False, opts, opts.db_table, None)
     470            joins.update(joins3)
     471
     472            # hack to get fieldname to order by. modify lookup_inner to supply this instead.
     473            field = where3[0].replace(' = %s', '')
     474            order_by.append('%s %s' % (field, order))
     475
    449476        # Add additional tables and WHERE clauses based on select_related.
    450477        if self._select_related:
    451478            fill_table_cache(opts, select, tables, where, opts.db_table, [opts.db_table])
     
    471498            sql.append(where and "WHERE " + " AND ".join(where))
    472499
    473500        # ORDER BY clause
    474         order_by = []
    475501        if self._order_by is not None:
    476502            ordering_to_use = self._order_by
    477503        else:
    478504            ordering_to_use = opts.ordering
     505        if order_by: # dont try to set up ordering again if already done
     506            ordering_to_use = []
    479507        for f in handle_legacy_orderlist(ordering_to_use):
    480508            if f == '?': # Special case.
    481509                order_by.append(backend.get_random_function_sql())
Back to Top