只是想知道我什么时候想使用一个和另一个.它们有何不同?
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 Noneq.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
发布评论