我有SQLAlchemy的數據模型(其他字段被遺漏):無效參照表而ORDER_BY施加
class Region(Base):
__tablename__ = 'region'
id = db.Column(db.Integer, primary_key=True)
class District(Base):
__tablename__ = 'district'
id = db.Column(db.Integer, primary_key=True)
region_id = db.Column(db.Integer, ForeignKey(Region.id))
region = relationship(Region)
和構建這個查詢:
session.query(District)\
.options(joinedload(District.region))\
.order_by(Region.name, Region.id)\
.slice(0, 25)
查詢發出錯誤ProgrammingError: (ProgrammingError) invalid reference to FROM-clause entry for table "region"
。調查後發現該錯誤的原始SQL原因。 ORDER BY
條款是不正確的:
SELECT district.id AS district_id,
district.name AS district_name,
district.region_id AS district_region_id,
region_1.id AS region_1_id
FROM district
LEFT OUTER JOIN region AS region_1 ON region_1.id = district.region_id
ORDER BY region.name, region.id
LIMIT 25
進入ORDER BY
子句使用region
,而不是正確的別名region_1
的,這引發了一個錯誤。
如何在這種情況下構建正確的查詢?