SQLAlchemy `History` class - why are the `added` and `deleted` attributes a list?

Viewed 94

I have created an event listener to capture changes to instances on one of my tables, like so:

Can someone kindly explain to me what the History class is and, more importantly, why the added and deleted attributes are lists?

@event.listens_for(Model, 'before_update')
def model_update(mapper, connection, target):

    """ signal when a Model is updated """

    # get state of model:
    state = inspect(target)

    # check for changes:
    for attr in state.attrs:

        # get history:
        hist = attr.load_history()  # <-- what is this class?
        
        # add changes to dictionary:
        old_value = hist.deleted   # <-- why is this a list?
        new_value = hist.added     # <-- why is this a list?

For context, I am trying to capture the changes to my models and save these changes to a different table (i.e. version history). Is it okay to do something like hist.deleted.pop()? Will hist.deleted always be a list? When, if ever, will it contain more than one item?

Further details: When I update an instance like so:

instance = db.query(Model).get(...) 

old_value = instance.some_field
new_value = "NEW"

instance.some_field = new_value

db.add(instance)
db.commit()

print("old_value:", old_value)
print("new_value:", new_value)

This will print:

old_value: OLD
new_value: NEW

But using history, these values will show up in a list:

old_value: ["OLD"]
new_value: ["NEW"]
1 Answers

What is attr.load_history() ?

Returns the current pre-flush change history for this attribute, via the History interface.

This represents a History interface. It returns the history of pre-flush changes (for the requested attribute). Each time the session is flushed, the history for each attribute is reset. (By default, the session is automatically flushed each time a request is invoked)

What is hist.deleted and hist.added ?

Representation of changes that have occurred on an attribute. There are 3 of them: added, unchanged and deleted:

added : the collection of elements added to the attribute

unchanged : the collection of elements that have not changed on the attribute

deleted : the collection of elements that have been deleted from the attribute

They are CONSTANTLY represented as an iterable sequence

Related