Python SqlAlchemy-按关系属性筛选

Python SqlAlchemy-按关系属性筛选,python,filter,sqlalchemy,foreign-keys,Python,Filter,Sqlalchemy,Foreign Keys,我没有太多的SQLAlchemy经验,我有一个问题,我无法解决。我试过搜索,也试过很多代码。 这是我的类(简化为最重要的代码): 我想查询所有患者,他们母亲的症状评分是(例如)==10 如前所述,我尝试了很多代码,但都不懂。在我看来,合乎逻辑的解决办法是 patients = Patient.query.filter(Patient.mother.phenoscore == 10) 因为,在输出时,您可以为每个元素访问.mother.phenoscore,但此代码不执行此操作 是否有(直接)可

我没有太多的SQLAlchemy经验,我有一个问题,我无法解决。我试过搜索,也试过很多代码。 这是我的类(简化为最重要的代码):

我想查询所有患者,他们母亲的症状评分是(例如)
==10

如前所述,我尝试了很多代码,但都不懂。在我看来,合乎逻辑的解决办法是

patients = Patient.query.filter(Patient.mother.phenoscore == 10)
因为,在输出时,您可以为每个元素访问
.mother.phenoscore
,但此代码不执行此操作

是否有(直接)可能通过关系的属性进行过滤(无需编写SQL语句或额外的join语句),我不止一次需要这种过滤


即使没有简单的解决方案,我也很高兴得到所有答案。

您必须查询与join的关系

您将从这个

关系使用方法中获得示例(更具可读性):

或加入(通常更快):


好消息:我最近制作了一个软件包,可以用“神奇的”字符串进行过滤/排序,所以现在您可以编写如下内容

Patient.where(mother___phenoscore=10)
它要短得多,特别是对于复杂的过滤器

Comment.where(post___public=True, post___user___name__like='Bi%')
希望您喜欢这个套餐


我在会话中使用它,但是您可以直接访问关系字段的另一种方法是

db_session.query(Patient).join(Patient.mother) \
    .filter(Patient.mother.property.mapper.class_.phenoscore==10)
我还没有测试过它,但我想这也会起作用

Patient.query.join(Patient.mother) \
    .filter(Patient.mother.property.mapper.class_.phenoscore==10)

这是关于如何查询关系的更一般的答案

relationship(..., lazy='dynamic', ...)
这允许您:

parent_obj.some_relationship.filter(ParentClass.some_attr==True).all()

patients=Patient.query.filter(Patient.mother.has(Patient.phenoscore==10))@user1105851
has()
既支持条件表达式作为未命名参数,也支持
filter\u by
样式的关键字参数。后者对我来说似乎更具可读性。@DenisOtkidach正确,但它应该是
phenoscore=10
filter_by
只接受相等关键字(因为它只是对它们进行**kwargs)@aruistant你是对的,编辑答案是错误的。使用any代替:patients=Patient.query.filter(Patient.mother.any(phenoscore=10))
Patient.query.join(Patient.mother) \
    .filter(Patient.mother.property.mapper.class_.phenoscore==10)
relationship(..., lazy='dynamic', ...)
parent_obj.some_relationship.filter(ParentClass.some_attr==True).all()