Cannot set/read Django simple history change reason

Viewed 1696

I'm using the simple_history package for Django and would like to record whether the user creates, updates or deletes a model object. I thought I'd use the history change reason for that purpose and in models.py do something like

def save(...):
    if not self.id:
        self.id = uuid()
        self.changeReason = 'create'
    else:
        self.changeReason = 'update'
    super(MyModel, self).save(...)

When I save the model this 'changeReason' field seems to be set (at least there are no errors) but when I try to read it in a test case like .history.first().instance.changeReason it complains that the field 'changeReason' does not exist. The history.first() call works so I do have a history record.

I have SIMPLE_HISTORY_HISTORY_CHANGE_REASON_USE_TEXT_FIELD = True in settings.py

I'm probably overlooking something basic but I can't seem to figure out what...

Thanks,

2 Answers

My bad... Setting self.changeReason = 'create' in the model is the right thing to do. The problem was incorrect checking of the change reason in my test case.

I checked

self.assertEqual(<object>.history.first().instance.changeReason, 'create')

but it should be

self.assertEqual(<object>.history.first().history_change_reason, 'create')

That passed the test :)

The above answer is correct for checking the changeReason; however, whether or not a record was created, updated, or deleted is already tracked in the history table by default in the history_type field.

Related