I have an ORM-mapped class Data
which includes a ‘valid_until’ (datetime) attribute I use for versioning of rows. This means that rows in the table can be duplicates with respect to some attributes, but the ‘valid_until’ attribute sets them apart, allowing me to identify which one is the most recent. The most recent such row has a future “infinity” ‘valid_until’ and all previous rows have the ‘valid_until’ set to when they were superseded.
I can write a custom insert method in the class to have the side-effect that when I insert a new row, it updates the ‘valid_to’ attribute of any existing row that would be a duplicate in order to supersede it. E.g.:
data = Data() # ORM-mapped object
data.insert()
Can I implement this in a way so that the custom insert behaviour is used when I call sqlalchemy.orm.Session.add
and perhaps sqlalchemy.orm.Session.bulk_save_objects
? I.e.:
session = sqlalchemy.orm.Session()
session.add(data)
session.commit()
This is so I would not have to make sure to use the custom Data.insert
method, but could just rely on the usual mechanisms of SQLAlchemy. I have looked for, for example an __insert__
method in ORM-mapped classes to override, but I have not found anything like that.
3