a way to cancel available query.order_by

Issue #1079 resolved
Former user created an issue

query has no official way to cancel an order_by. query.order_by(whatever) only adds to existing order list, it never removes. this is any version 0.3/0.4/0.5 - the possible q=q.order_by() and q=q.order_by(None) do nothing

here a patch to make q.order_by(None) cancel any previous order_by, so q.order_by(a).order_by(None).order_by(b) orders by b and not by a,b

here a test case:

from sqlalchemy import * from sqlalchemy.orm import * m = MetaData('sqlite:///') m.bind.echo=True t = Table( 't', m, Column('a', Integer), Column('b', Integer, primary_key=True) ) class T(object): pass mapper( T,t) m.create_all() s = create_session() q = s.query(T).order_by( T.a).order_by( None).order_by( T.b) print q.all()

the result query is: SELECT t.a AS t_a, t.b AS t_b FROM t ORDER BY t.a, t.b

adding something like this at beginning of Query.order_by() would fix it: if not criterion: self._order_by = False return

the result query is what expected: SELECT t.a AS t_a, t.b AS t_b FROM t ORDER BY t.b

az()svilendobrev_com

patches attached

Comments (6)

  1. Mike Bayer repo owner

    im pretty strong -1 on this. Because:

    • what about filter()?
    • what about filter_by()?
    • what about options()?
    • what about group_by()?
    • what about limit() ?
    • everything else

    The Query's state is non-reversible. I can't think of any reason why order_by() would get "special meaning" in this regard and all the other methods do not.

    If you need a Query that does not have a particular ordering, keep a reference to the original Query before order_by() is applied.

  2. Michael Trier

    I'm actually +0 on this. I can see that you might define a default order_by but then decide you need to override it. This sort of situation doesn't occur with things like filter, etc... So it's not exactly the same thing.

  3. Mike Bayer repo owner
    • changed milestone to 0.5.0

    OK, because you can in fact have default_order_by on a mapper() or relation(), that's why its different from the others. so its accepted ! patch for 0.5 and 0.4.

  4. Log in to comment