force object to be `dirty` in sqlalchemy

后端 未结 2 742
遥遥无期
遥遥无期 2020-12-18 21:25

Is there a way to force an object mapped by sqlalchemy to be considered dirty? For example, given the context of sqlalchemy\'s Object Relational Tutorial the p

2条回答
  •  伪装坚强ぢ
    2020-12-18 21:48

    I came across the same problem recently and it was not obvious.

    Objects themselves are not dirty, but their attributes are. As SQLAlchemy will write back only changed attributes, not the whole object, as far as I know.

    If you set an attribute using set_attribute and it is different from the original attribute data, SQLAlchemy founds out the object is dirty (TODO: I need details how it does the comparison):

       from sqlalchemy.orm.attributes import set_attribute
       set_attribute(obj, data_field_name, data)
    

    If you want to mark the object dirty regardless of the original attribute value, no matter if it has changed or not, use flag_modified:

       from sqlalchemy.orm.attributes import flag_modified
       flag_modified(obj, data_field_name)
    

提交回复
热议问题