Force object will be dirty in sqlalchemy

Is there a way to make the object displayed by sqlalchemy be considered dirty ? For example, given the context of the sqlalchemy Object Relational Tutorial , the problem is being demonstrated,

 a=session.query(User).first() a.__dict__['name']='eh' session.dirty 

 IdentitySet([]) 

I am looking for a way to make user a enter a dirty state.

This problem occurs because the class that is displayed using sqlalchemy manages the getter / setter attribute methods, and this prevents sqlalchemy changes from being logged.

+6
source share
2 answers

Recently, I ran into the same problem, and this was not obvious.

The objects themselves are not polluted, but their attributes. As far as I know, SQLAlchemy will only write changed attributes, not the entire object.

If you set the attribute using set_attribute and are different from the attribute's original data, SQLAlchemy detects that the object is dirty (TODO: I need details on how it does the comparison):

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

If you want to mark an object dirty regardless of the initial value of the attribute, regardless of its change or not, use flag_modified :

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

The flag_modified approach works if the attribute is known to have a value. SQLAlchemy Documentation Status :

Mark the instance attribute as "modified."

This sets the “modified flag in the instance and sets an unconditional change event for this attribute. The attribute must have a value, in addition an InvalidRequestError occurs.

Starting with version 1.2, if you want to mark the entire instance, then flag_dirty is the solution :

Mark the instance as "dirty without any specific attribute."

0
source

Source: https://habr.com/ru/post/985808/


All Articles