When to use SQLAlchemy .get() vs .filter(Foo.ID == primary_key_id).first()

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)