Sqlalchemy session.refresh does not refresh object

后端 未结 4 754
[愿得一人]
[愿得一人] 2021-02-05 17:27

I have the following mapping (straight from SA examples):

class User(Base):
    __tablename__ = \'users\'

    id = Column(Integer, primary_key=True)
    name =          


        
相关标签:
4条回答
  • 2021-02-05 17:53

    From the docs:

    Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction

    SQLAlchemy uses a transactional unit of work model, wherein each transaction is assumed to be internally consistent. A session is an interface on top of a transaction. Since a transaction is assumed to be internally consistent, SQLAlchemy will only (well, not quite, but for ease of explanation...) retrieve a given piece of data from the database and update the state of the associated objects once per transaction. Since you already queried for the object in the same session transaction, SQLAlchemy will not update the data in that object from the database again within that transaction scope. If you want to poll the database, you'll need to do it with a fresh transaction each time.

    0 讨论(0)
  • 2021-02-05 17:59

    session.refresh() didn't work for me either. Even though I saw a low-level SELECT the object was not updated after the refresh.

    This answer https://stackoverflow.com/a/11121788/562267 hints to doing an actual commit/rollback to reset the session, and that worked for me:

    user_1 = session.query(User).filter(User.id==1).one()
    user_1.name # This prints: u'user1'
    # update the database from another client here
    session.commit()
    user_1 = session.query(User).filter(User.id==1).one()
    user_1.name # Should be updated now.
    
    0 讨论(0)
  • 2021-02-05 18:09

    Merge the session.

    u = session.query(User).get(id)
    u.name = 'user1_changed'
    u = session.merge(u)
    

    This will update the database and return the newer object.

    0 讨论(0)
  • 2021-02-05 18:19

    Did you try with "expire" as described in the official doc:

    http://docs.sqlalchemy.org/en/rel_0_8/orm/session.html#refreshing-expiring

    # expire objects obj1, obj2, attributes will be reloaded
    # on the next access:
    session.expire(user_1)
    session.refresh(user_1)
    

    Using expire on a object results in a reload that will occur upon next access.

    0 讨论(0)
提交回复
热议问题