Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force object to be `dirty` in sqlalchemy

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 problem is demonstrated,

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

yielding,

IdentitySet([])

i am looking for a way to force the user a into a dirty state.

This problem arises because the class that is mapped using sqlalchemy takes control of the attribute getter/setter methods, and this preventing sqlalchemy from registering changes.

like image 837
alex Avatar asked Apr 23 '15 17:04

alex


People also ask

What is _sa_instance_state in SQLAlchemy?

_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance.

What does all () do in SQLAlchemy?

all() method. The Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present.

What is lazy true in SQLAlchemy?

Typically when you query the database, the data get loaded at once; however, lazy parameter allows you to alternate the way they get loaded. lazy = 'select' (or True)

What does Session flush do SQLAlchemy?

session. flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.


1 Answers

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)
like image 79
Mikko Ohtamaa Avatar answered Sep 22 '22 15:09

Mikko Ohtamaa