On 05/25/2016 11:16 PM, Mike Bayer wrote:
Assuming you want more, phrase this as an input/output situation for
me. Give me input and what the desired output you want is. The big
guns here are a function called corresponding_column() which I can
show you how to use if that's what's needed
Here is the full "input":
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
engine = sa.create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()
class Foo(Base):
__tablename__ = 'foo'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
def __repr__(self):
return 'Foo(id=%s, name="%s")' % (self.id, self.name)
class Bar(Base):
__tablename__ = 'bar'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
foo_id = sa.Column(sa.Integer, sa.ForeignKey('foo.id'),
nullable=False)
foo = sa.orm.relationship('Foo', backref='bars')
Base.metadata.create_all(engine)
Session = sa.orm.sessionmaker(bind=engine)
session = Session()
baz = Foo(name='baz')
qux = Foo(name='qux')
session.add(baz)
session.add(qux)
session.add(Bar(name='spam', foo=baz))
session.add(Bar(name='parrot', foo=baz))
session.commit()
q = session.query(Foo).outerjoin(Bar)
q = q.order_by('name')
print(q)
Here is the output:
SELECT foo.id AS foo_id, foo.name AS foo_name
FROM foo
LEFT OUTER JOIN bar
ON foo.id = bar.foo_id
ORDER BY *bar.name*
While desired output is ORDER BY foo.name.
Here is my solution:
def get_leftmost(selectable):
current = selectable.froms[0]
while True:
if hasattr(current, 'left'):
current = current.left
elif hasattr(current, 'append'):
current = current[0]
elif hasattr(current, 'columns'):
return current
else:
raise AssertionError
print(q.order_by(get_leftmost(q.statement).c.name))
It gives me:
SELECT foo.id AS foo_id, foo.name AS foo_name
FROM foo LEFT OUTER
JOIN bar ON foo.id = bar.foo_id
ORDER BY *foo.name*
Which is what I want. But /a)/ it's too hacky /b)/ I'm not sure if froms
guarantees any ordering.
--
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.