sqlalchemy

时间:2016-03-09 02:19:19

标签: python sqlalchemy

我有@hybrid_property引用嵌套关系self.establishment_type.establishment_base_type.name == 'QSR'。它适用于assert location.is_qsr == True中的Location对象,但不适用于过滤器。我尝试添加@is_qsr.expression函数,但无法使其中任何一个正常工作。如何启用query(Location).filter(Location.is_qsr == True)

等过滤器
class Location(Base):
    __tablename__ = 'houses'
    id = Column(Integer, primary_key=True)
    establishment_type_id = Column(
        Integer, ForeignKey('establishment_types.id')
    )
    establishment_type = relationship('EstablishmentType')

    @hybrid_property
    def is_qsr(self):
        if self.establishment_type:
            if self.establishment_type.establishment_base_type:
                return self.establishment_type.establishment_base_type.name == 'QSR'

        return False

class EstablishmentType(Base):
    __tablename__ = 'establishment_types'
    id = Column(Integer, primary_key=True)

    establishment_base_type_id = Column(
        Integer, ForeignKey('establishment_base_types.id')
    )
    establishment_base_type = relationship('EstablishmentBaseType')

class EstablishmentBaseType(Base):
    __tablename__ = 'establishment_base_types'
    id = Column(Integer, primary_key=True)

1 个答案:

答案 0 :(得分:1)

您可以对关系使用.has

allows

这不会产生世界上最有效的查询(它会产生@is_qsr.expression def is_qsr(cls): return cls.establishment_type.has( EstablishmentType.establishment_base_type.has( EstablishmentBaseType.name == "QSR")) )但是一个体面的优化器应该能够解决它。