何时使用 SQLAlchemy .get() 与 .filter(Foo.ID == primary

编程入门 行业动态 更新时间:2024-10-27 07:16:06
本文介绍了何时使用 SQLAlchemy .get() 与 .filter(Foo.ID == primary_key_id).first()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

只是想知道我什么时候想使用一个和另一个.它们有何不同?

Just curious about when I would want to use one vs the other. How are they different?

我们已经设置了我们的系统,我们可以做到这一点:

We have our system set up such that we can do this:

my_user = User.query().filter(User.ID == 5).first()

my_user = User.query().get(5)

推荐答案

这两行是一回事.只有引发的异常不同.实际上,get() 是在 one() 之上实现的.如果您的 filter() 返回的不仅仅是结果,那将会有所不同,但这在您的情况下确实是不可能的.

Those two lines are the same thing. Only exceptions raised differ. In fact, get() is implemented on top of one(). There would be a difference if your filter() returned more than a result, but this is indeed not possible in your case.

顺便说一下,SQL 没有 GET 操作,它只有 SELECT(带有可选的 LIMIT).

By the way, SQL does not have a GET operation, it only has SELECT (with optional LIMIT).

sqlalchemy/:

sqlalchemy/orm/query.py:

def get(self, ident): ... return self._get_impl(ident, loading.load_on_ident)

sqlalchemy/orm//a>:

sqlalchemy/orm/loading.py:

def load_on_ident(query, key, refresh_state=None, lockmode=None, only_load_props=None): ... try: return q.one() except orm_exc.NoResultFound: return None

q.one() 依次调用 q.one_or_none().

q.one() in turn calls q.one_or_none().

现在比较first() 使用 one_or_none():

def first(self): ... ret = list(self[0:1]) if len(ret) > 0: return ret[0] else: return None def one_or_none(self): ... ret = list(self) l = len(ret) if l == 1: return ret[0] elif l == 0: return None else: raise orm_exc.MultipleResultsFound( "Multiple rows were found for one_or_none()")

因此,first() 执行带有 LIMIT 的 SELECT,one_or_none() 执行无限制的 SELECT.但是,正如我们已经说过的,无论有没有 LIMIT,查询的结果都不会改变,因此两者是等价的.

Therefore, first() executes a SELECT with a LIMIT, one_or_none() executes an unlimited SELECT. But, as we already said, either with or without LIMIT the result of the query cannot change, therefore the two are equivalent.

更多推荐

何时使用 SQLAlchemy .get() 与 .filter(Foo.ID == primary

本文发布于:2023-10-16 15:52:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498032.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:filter   SQLAlchemy   Foo   primary   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!