Can SQLAlchemy's session.merge() update its result with newer data from the database?

后端 未结 2 532
野的像风
野的像风 2021-02-01 05:59

The SQLAlchemy documentation says \"session.merge() reconciles the current state of an instance and its associated children with existing data in the database\".

Does th

2条回答
  •  没有蜡笔的小新
    2021-02-01 06:07

    One thing I noticed about merge is that even accessing a field on the unattached object will cause it to be modified during a merge.

    For example, if I have a simple class

    class X(Base):
        __tablename__= 'x'
    
        id = Column(Integer, primary_key=True)
        name = Column(String)
        value = Column(String)
    

    and a row

    (1, 'foo', 'bar')
    

    then the following seems to merge nicely:

    x = X(id=1)
    merged_x = session.merge(x)
    
    print merged_x.name         # 'foo'
    print merged_x.description  # 'bar'
    

    But if I even read name or description, this happens

    x = X(id=1)
    print x.name                # None
    
    merged_x = session.merge(x)
    
    print merged_x.name         # None
    print merged_x.description  # 'bar'
    

    This is counterintuitive and, I'd argue, incorrect. Is there a way to turn off this behavior? Apparently the mere presence of an attribute in __dict__ causes this to happen. This 'feature' should be noted in the documentation.

提交回复
热议问题