SqlAlchemy - 根据关联属性进行过滤

11 浏览
0 Comments

SqlAlchemy - 根据关联属性进行过滤

我对SQLAlchemy没有太多经验,也遇到了一个无法解决的问题。我尝试过搜索和尝试了很多代码。

这是我的类(仅包含最重要的代码):

class Patient(Base):
    __tablename__ = 'patients'
    id = Column(Integer, primary_key=True, nullable=False)
    mother_id = Column(Integer, ForeignKey('patients.id'), index=True)
    mother = relationship('Patient', primaryjoin='Patient.id==Patient.mother_id', remote_side='Patient.id', uselist=False)
    phenoscore = Column(Float)

我想查询所有母亲的`phenoscore`为10的患者。

我尝试了很多代码,但是没有成功。在我看来,逻辑上的解决方案应该是:

patients = Patient.query.filter(Patient.mother.phenoscore == 10)

因为在输出时,可以访问每个元素的`.mother.phenoscore`属性,但是这段代码没有实现。

有没有一种(直接的)方法可以根据关系属性进行过滤(不需要编写SQL语句或额外的连接语句),我需要多次使用这种过滤器。

即使没有简单的解决方案,我也很乐意接收所有答案。

0