well, a "default", I disagree the problem is that simple. Because we have a "default", Mapper.order_by, but all those cases I mentioned, no idea.

If we wanted to say that hey, "default" only means, "I'm querying for a single entity in full, alone, otherwise no order_by", I guess that's something. I can un-deprecate mapper.order_by if people wanted to really work out what it should do always.

Anyway, if "default" is really something kind of arbitrary here, you can use the before_compile event hook for Query.

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import event

Base = declarative_base()


class A(Base):
    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)


default_order_by = {
    A: A.id
}


@event.listens_for(Query, "before_compile", retval=True)
def _default_order_by(query):
    entity = query.column_descriptions[0]['entity']
    if entity in default_order_by:
        query = query.order_by(default_order_by[entity])
    return query

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)


s = Session(e)
s.add_all([A(id=1), A(id=2)])
s.commit()

s.query(A).all()

On 05/09/2017 03:36 AM, Chris Withers wrote:
Gotcha. Is there any way to specify a default ordering for queries against a model?

(similar to that offered by the Django ORM?)

cheers,

Chris


On 08/05/2017 23:51, mike bayer wrote:
because, it only works for a really simplistic case, and for all the other cases, I have no idea what it currently does, nor what it should do.

Assume A and B have order_by. I have no idea what the output is, or should be, for:

s.query(A, B)
s.query(B, A)
s.query(A).join(B)
s.query(A).select_from(B).join(A)
s.query(A, B).select_from(B).join(A)
s.query(A.id)
s.query(A, B.id)
s.query(A.id, B)
s.query(A.id, B.id)
s.query(B.id, A.id)

etc





On 05/08/2017 06:21 AM, Chris Withers wrote:
Hi All,

I see mapper.order_by is deprecated in the latest release. Why is that?

cheers,

Chris




--
SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

To post example code, please provide an MCVE: Minimal, Complete, and Verifiable 
Example.  See  http://stackoverflow.com/help/mcve for a full description.
--- You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to