force object to be `dirty` in sqlalchemy

后端 未结 2 740
遥遥无期
遥遥无期 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)
    
    0 讨论(0)
  • 2020-12-18 21:55

    The flag_modified approach works if one know that attribute have a value present. SQLAlchemy documentation states:

    Mark an attribute on an instance as ‘modified’.

    This sets the ‘modified’ flag on the instance and establishes an unconditional change event for the given attribute. The attribute must have a value present, else an InvalidRequestError is raised.

    Starting with version 1.2, if one wants to mark an entire instance then flag_dirty is the solution:

    Mark an instance as ‘dirty’ without any specific attribute mentioned.

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