Python .one() 和 .first() 有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29161730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:10:03  来源:igfitidea点击:

What is the difference between .one() and .first()

pythonsqlalchemyflask-sqlalchemy

提问by Reena Shirale

What is the difference between oneand firstmethods in SQLAlchemy

SQLAlchemy 中的onefirst方法有什么区别

采纳答案by Martijn Pieters

Query.one()requires that there is only oneresult in the result set; it is an error if the database returns 0 or 2 or more results and an exception will be raised.

Query.one()要求结果集中只有一个结果;如果数据库返回 0 或 2 个或更多结果,则为错误并引发异常。

Query.first()returns the first of a potentially larger result set (adding LIMIT 1to the query), or Noneif there were no results. No exception will be raised.

Query.first()返回可能更大的结果集(添加LIMIT 1到查询)中的第一个,或者None如果没有结果。不会引发任何异常。

From the documentation for Query.one():

从文档中Query.one()

Return exactly one result or raise an exception.

只返回一个结果或引发异常。

and from Query.first():

来自Query.first()

Return the first result of this Query or Noneif the result doesn't contain any row.

如果结果不包含任何行,则返回此 Query 的第一个结果或 None

(emphasis mine).

(强调我的)。

In terms of a Python list, one()would be:

就 Python 列表而言,one()将是:

def one(lst):
    if not lst:
        raise NoResultFound
    if len(lst) > 1:
        raise MultipleResultsFound
    return lst[0]

while first()would be:

first()将是:

def first(lst):
    return lst[0] if lst else None

There is also a Query.one_or_none()method, which raises an exception only if there are multiple results for the query. Otherwise it'll return the single result, or Noneif there were no results.

还有一种Query.one_or_none()方法,仅当查询有多个结果时才会引发异常。否则它将返回单个结果,或者None如果没有结果。

In list terms, that'd be the equivalent of:

在列表中,这相当于:

def one_or_none(lst):
    if not lst:
        return None
    if len(lst) > 1:
        raise MultipleResultsFound
    return lst[0]