你能在SQLAlchemy中为关系连接的on子句添加条件吗?

时间:2018-01-05 20:38:43

标签: python sql-server sqlalchemy

假设我有以下两个SQLAlchemy ORM类:

import sqlalchemy as sa

class Address(Base):
    __tablename__ = 'DimAddress'

    AddressKey = sa.Column(sa.Integer, primary_key=True)
    # ... columns ...

class DealerOrganisation(Base):
    __tablename__ = 'DimDealerOrganisation'

    DealerOrganisationKey = sa.Column(sa.Integer, primary_key=True)
    # ... columns ...
    DealerOrganizationAddressKey = sa.Column(sa.Integer, sa.ForeignKey('DimAddress.AddressKey'), nullable=False)
    # ... columns ...

    address = relationship('Address')

我可以获得经销商组织及其地址(如果有),如下所示:

session = Session()
query = session.query(DealerOrganisation).outerjoin(DealerOrganisation.address).options(contains_eager(DealerOrganisation.address))

这给我的SQL大致如下:

SELECT *
FROM DimDealerOrganisation
LEFT JOIN DimAddress ON AddressKey = DealerOrganizationAddressKey

但是,如果我只想对相关对象的子集进行ORM查询,那该怎么办:

SELECT *
FROM DimDealerOrganisation
LEFT JOIN DimAddress ON AddressKey = DealerOrganizationAddressKey AND ZipCode = '90210'

也就是说,我想要所有经销商,但如果邮政编码是90210,我只想要他们的地址。据我所知,join()和outerjoin()让你指定关系或显式条件,但不是两个。在这个人为的例子中,我可以使用显式条件并返回行而不是ORM对象,但在涉及多个表和一对多关系的真实查询中它将是不实用的。我想为on子句添加其他条件,但仍然填充返回的DealerOrganisation对象的address属性。这可能吗?

1 个答案:

答案 0 :(得分:0)

您将要在联接中使用and_ operator from SQLAlchemy。我认为它看起来像:

session = Session()
session.query(Table1).join(Table2, and_(Table1.address==Table2.address, Table1.zip == '90210'), isouter=True)