SqlAlchemy - Filtering by Relationship Attribute

折月煮酒 提交于 2019-11-28 03:38:14

Use method has() of relationship (more readable):

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

or join (usually faster):

patients = Patient.query.join(Patient.mother, aliased=True)\
                    .filter_by(phenoscore=10)

You have to query the relationsip with join

You will get the example from this Self-Referential Query Strategies

Good news for you: I recently made package that gives you filtering/sorting with "magical" strings as in Django, so you can now write something like

Patient.where(mother___phenoscore=10)

It's a lot shorter, especially for complex filters, say,

Comment.where(post___public=True, post___user___name__like='Bi%')

Hope you will enjoy this package

https://github.com/absent1706/sqlalchemy-mixins#django-like-queries

I used it with sessions, but an alternate way where you can access the relationship field directly is

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

I have not tested it, but I guess this would also work

Patient.query.join(Patient.mother) \
    .filter(Patient.mother.property.mapper.class_.phenoscore==10)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!