通过另一个表在两个表之间建立关系

Make a relationship between two tables though another

class Condominium(db.Model):
    __tablename__ = 'condominiums'
    id = db.Column(db.Integer, primary_key=True)
    properties = db.relationship('Property', backref='condominiums')

class Property(db.Model):
    __tablename__ = 'properties'
    id = db.Column(db.Integer, primary_key=True)
    condominium_id = db.Column(db.Integer, db.ForeignKey('condominiums.id'))
    listings = db.relationship('Listing', backref='property')

class Listing(db.Model):
    __tablename__ = 'listings'
    id = db.Column(db.Integer, primary_key=True)
    property_id = db.Column(db.Integer, db.ForeignKey('properties.id'))

我想列出给定 condominium 的所有 listings,如下所示:

SELECT listings.* FROM condominiums
INNER JOIN properties ON properties.condominium_id = condominiums.id
INNER JOIN listings ON listings.property_id = properties.id
WHERE condominiums.id = 1;

我希望能够得到这样的 listing collection:

condominium = Condominium.query.get(1)
listings = condominium.listings

我如何使用 SQLAlchemy 实现这一点?可能吗?

假设 Condominium 是 1:M 到 属性,即 1:M 到 Listing 并且所有外键都定义明确,您可以获得 ID 为 123 的 Condominium 的所有列表,因此:

session.query(Listing).join(Property).join(Condominium).filter(Condominium.id=123)