从SQLalchemy和Flask中的相关列表中查询 [英] Querying from list of related in SQLalchemy and Flask

查看:87
本文介绍了从SQLalchemy和Flask中的相关列表中查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有User,其中has-one Person.所以User.personPerson.
我正在尝试从Person的列表中获取User的列表.

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.

我尝试了以下操作:

>>> 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.

获取User列表(其中User.person在该people列表中)的最佳方法是什么?

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

推荐答案

该错误消息会告诉您,您需要对外键使用in_:

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()

因为无论如何都要查询两者,所以最好先做一个合并的加载,然后再让人们使用Python:

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]

这篇关于从SQLalchemy和Flask中的相关列表中查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆