[英]nested relationship in hybrid_property in sqlalchemy
I have a @hybrid_property
which references a nested relationship self.establishment_type.establishment_base_type.name == 'QSR'
. 我有一个@hybrid_property
,它引用嵌套关系self.establishment_type.establishment_base_type.name == 'QSR'
。 It works on a Location object as in assert location.is_qsr == True
, but not in a filter. 它像在assert location.is_qsr == True
一样在Location对象上工作,但不在过滤器中工作。 I have tried adding a @is_qsr.expression
function, but can't get any of them working. 我尝试添加一个@is_qsr.expression
函数,但是其中任何一个都无法正常工作。 How can I enable a filter such as query(Location).filter(Location.is_qsr == True)
? 如何启用过滤器,例如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)
You can use .has
on relationships: 您可以对关系使用.has
:
@is_qsr.expression
def is_qsr(cls):
return cls.establishment_type.has(
EstablishmentType.establishment_base_type.has(
EstablishmentBaseType.name == "QSR"))
This doesn't produce the most efficient query in the world (it does a EXISTS (SELECT 1 FROM ...)
) but a decent optimizer should be able to figure it out. 这不会产生世界上最高效的查询(它会执行EXISTS (SELECT 1 FROM ...)
),但是一个不错的优化程序应该能够弄清楚它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.