简体   繁体   English

如何调用限制为 1 的 SQLAlchemy 查询?

[英]How can I invoke an SQLAlchemy query with limit of 1?

I have code like this:我有这样的代码:

thing = thing.query.filter_by(id=thing_id).limit(1).all()[0]

all()[0] feels a bit messy and redundant in the limit(1) case. all()[0]limit(1)情况下感觉有点混乱和多余。 Is there a more terse (and/or otherwise optimal) way to achieve this?是否有更简洁(和/或其他最佳)的方法来实现这一目标?

There's first() : first()

first() applies a limit of one and returns the first result as a scalar first()应用一个限制,并将第一个结果作为标量返回

Thus: 从而:

thing = thing.query.filter_by(id=thing_id).first()

Jwodder's answer will, indeed, return the first result as a scalar, but SQLAlchemy provides a couple other functions that may better suit your needs, so I have listed and explained all of them: 的确,Jwodder的答案将以标量形式返回第一个结果,但是SQLAlchemy提供了其他两个更适合您需要的函数,因此,我列出并解释了所有这些函数:

first() will pull the first row returned, or None if no row is returned. first()将拉出返回的第一行;如果不返回任何行,则返回None

one() will pull 1 row, but it MUST only pull one row: it will error out if the number of returned rows from your query is not 1. one()将拉出1行,但必须仅拉出一行:如果从查询返回的行数不是1,它将出错。

one_or_none() will essentially do a one() , but instead of erroring out will return None if no rows are returned. one_or_none()本质上将执行one() ,但是如果没有返回任何行,则不会出错,将返回None This will still error out if more than one rows is returned. 如果返回多行,仍然会出错。

The documentation for all of these can be found here: http://docs.sqlalchemy.org/en/latest/orm/query.html 所有这些文档都可以在以下位置找到: http : //docs.sqlalchemy.org/en/latest/orm/query.html

First of all, agree and support other answers. 首先,同意并支持其他答案。

However, it looks like that your queries are for the primary key column. 但是,您的查询似乎是针对primary key列的。 If this is the case, the most straightforward way of making such a query would be to simply call get() : 如果是这种情况,进行这种查询的最直接方法就是简单地调用get()

thing = Thing.query.get(thing_id)

SQLAlchemy 核心为查询提供了一个.limit(1) 运算符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM