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.
By the way, SQL does not have a GET operation, it only has SELECT (with optional LIMIT).
sqlalchemy/orm/query.py:
def get(self, ident):
...
return self._get_impl(ident, loading.load_on_ident)
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()
in turn calls q.one_or_none()
.
Now compare first()
with 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()")
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…