2

我正在使用 Django 的 simple_history 包,并想记录用户是否创建、更新或删除模型对象。我以为我会为此目的使用历史更改原因,并在 models.py 中执行类似的操作

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

当我保存模型时,这个“changeReason”字段似乎已设置(至少没有错误),但是当我尝试在 .history.first().instance.changeReason 之类的测试用例中读取它时,它抱怨该字段“ changeReason' 不存在。history.first() 调用有效,所以我确实有历史记录。

我在 settings.py 中有 SIMPLE_HISTORY_HISTORY_CHANGE_REASON_USE_TEXT_FIELD = True

我可能忽略了一些基本的东西,但我似乎无法弄清楚是什么......

谢谢,

4

2 回答 2

0

我的错...在模型中设置 self.changeReason = 'create' 是正确的做法。问题是在我的测试用例中对更改原因的检查不正确。

我检查了

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

但应该是

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

通过了测试:)

于 2018-11-15T21:31:04.370 回答
0

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.

于 2018-12-12T19:56:08.743 回答