order_by with property of related table

15 views
Skip to first unread message

gwozdziu

unread,
Jul 20, 2011, 12:18:34 PM7/20/11
to sqlalchemy
Hi!

I have two tables: A and B defined something like that:

A:
Column('id', Integer, primary_key=True),
Column('name', Unicode(256)),
Column('b_id', Integer, ForeignKey('b.id'))

B:
Column('id', Integer, primary_key=True),
Column('name', Unicode(256)),

mapper of A is created with:
properties={
'b': relation(B, primaryjoin=A.b_id == B.id, lazy=False),
}
(lazy = False is important in this case)

How can I select all elements from A sorted by B.name? I checked that
I can't use
SESSION.query(A).order_by(B.name)
because it's not working - query(A) consist of JOIN with B table and B
table has alias B_1 in this query and sqlalchemy interprets
order_by(B.name) as ORDER BY B.name but there is no B alias in
query(A).

Gunnlaugur Briem

unread,
Jul 27, 2011, 6:16:02 AM7/27/11
to sqlal...@googlegroups.com
Hi,

you need to join explicitly on A.b:

SESSION.query(A).join(A.b).order_by(B.name)


Regards,

- Gulli

Reply all
Reply to author
Forward
0 new messages