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

后端 未结 3 1116
眼角桃花
眼角桃花 2020-12-10 13:43

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 = U         


        
3条回答
  •  既然无缘
    2020-12-10 14:44

    One important addition to Andrea Corbellini's answer: get can provide a performance boost by retrieving the object from memory if it already exists in the SQLAlchemy session.

    sqlalchemy/orm/query.py:

        :meth:`~.Query.get` is special in that it provides direct
        access to the identity map of the owning :class:`.Session`.
        If the given primary key identifier is present
        in the local identity map, the object is returned
        directly from this collection and no SQL is emitted,
        unless the object has been marked fully expired.
        If not present,
        a SELECT is performed in order to locate the object.
    

    Additionally, get will do a database I/O (i.e. SELECT statement) to refresh the object, if it has expired within the session:

    sqlalchemy/orm/query.py:

        :meth:`~.Query.get` also will perform a check if
        the object is present in the identity map and
        marked as expired - a SELECT
        is emitted to refresh the object as well as to
        ensure that the row is still present.
        If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
    

提交回复
热议问题