如何限制/偏移 sqlalchemy orm 关系的结果?
如果我有一个用户模型和文章模型,用户和文章是一对多关系。所以我可以访问这样的文章,
user = session.query(User).filter(id=1).one()
print user.articles
但这将列出用户的所有文章,如果我想将文章限制为 10 篇怎么办?在rails中有一个all()
方法,其中可以有限制/偏移量。在sqlalchemy中还有一个all()
方法,但是不带参数,如何实现呢?
编辑:
似乎 user.articles[10:20]
是有效的,但 sql 在查询中没有使用 10 / 20 。那么实际上它会加载所有匹配的数据,并在 python 中进行过滤?
in case i have a user Model and article Model, user and article are one-to-many relation. so i can access article like this
user = session.query(User).filter(id=1).one()
print user.articles
but this will list user's all articles, what if i want to limit articles to 10 ? in rails there is an all()
method which can have limit / offset in it. in sqlalchemy there also is an all()
method, but take no params, how to achieve this?
Edit:
it seems user.articles[10:20]
is valid, but the sql didn't use 10 / 20 in queries. so in fact it will load all matched data, and filter in python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案是使用
动态
关系,如集合配置技术 部分。通过指定关系,
您可以编写
user.articles.limit(10)
,它将生成并执行查询以获取用户的最后十篇文章。或者,如果您愿意,您可以使用[x:y]
语法,这将自动生成LIMIT
子句。性能应该是合理的,除非您想要为 100 个左右的用户查询过去 10 篇文章(在这种情况下,至少有 101 个查询将发送到服务器)。
The solution is to use a
dynamic
relationship as described in the collection configuration techniques section of the SQLAlchemy documentation.By specifying the relationship as
you can then write
user.articles.limit(10)
which will generate and execute a query to fetch the last ten articles by the user. Or you can use the[x:y]
syntax if you prefer which will automatically generate aLIMIT
clause.Performance should be reasonable unless you want to query the past ten articles for 100 or so users (in which instance at least 101 queries will be sent to the server).