在另外两个表之间建立关系

时间:2015-01-22 20:43:14

标签: python flask sqlalchemy flask-sqlalchemy

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'))

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

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集合:

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

如何使用SQLAlchemy实现这一目标?有可能吗?

1 个答案:

答案 0 :(得分:1)

假设Condominium是1:M到物业,上市时间为1:M且所有外国钥匙都是明确定义的,您可以获得所有公寓的房源,其中ID为123:

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