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

前端 未结 1 1112
面向向阳花
面向向阳花 2020-12-09 16:33

Models

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, ForeignKey
from s         


        
相关标签:
1条回答
  • 2020-12-09 16:41

    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)
    
    0 讨论(0)
提交回复
热议问题