SQLAlchemy: How to order query results (order_by) on a relationship's field? SQLAlchemy: How to order query results (order_by) on a relationship's field? python python

SQLAlchemy: How to order query results (order_by) on a relationship's field?


SQLAlchemy wants you to think in terms of SQL. If you do a query for "Base", that's:

SELECT * FROM base

easy. So how, in SQL, would you select the rows from "base" and order by the "name" column in a totally different table, that is, "player"? You use a join:

SELECT base.* FROM base JOIN player ON base.ownerid=player.id ORDER BY player.name

SQLAlchemy has you use the identical thought process - you join():

session.query(Base).join(Base.owner).order_by(Player.name)