Querying from list of related in SQLalchemy and Flask

余生颓废 提交于 2019-12-12 08:42:44

问题


I have User which has-one Person. So User.person is a Person.
I am trying to get a list of User from a list of Person.

I tried the following:

>>> people = Person.query.filter().limit(3)
<flask_sqlalchemy.BaseQuery object at 0x111c69bd0>

>>> User.query.filter(User.person.in_(people)).all()
NotImplementedError: in_() not yet supported for relationships.  For a simple many-to-one, use in_() against the set of foreign key values.

What is the best way to get a list of Users where User.person is in that list of people?


回答1:


As the error message helpfully tells you, you need to use in_ against the foreign keys instead:

User.query.join(User.person).filter(Person.id.in_(p.id for p in people)).all()

Since you're going to query for both anyway, might be better to do a joined load and then get the people using Python:

people = Person.query.join(Person.user).options(db.contains_eager(Person.user)).limit(3).all()
users = [p.user for p in people]


来源:https://stackoverflow.com/questions/23436095/querying-from-list-of-related-in-sqlalchemy-and-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!