我正在尝试实现方法,该方法将在"编辑日期"列中添加另一列的编辑日期。就像我连续更改用户名一样,同时在"编辑日期"上出现类似"23.08.18"的内容。最好的方法是什么?
首先,将模型中的editing_date
定义为 DateTime 列。
然后,可以在模型视图类定义中重写on_model_change()
方法。只需将以下内容放在您的模型视图类中即可
from datetime import datetime
on_model_change(form, model, is_created):
if not is_created: # True if model was created and to False if edited
# you only want this to run when model is edited so we are using not operator
model.edit_date = datetime.utcnow()
on_nodel_view()
在创建或更新模型并将更改提交到数据库之前执行一些操作。每当要在将更改提交到数据库之前运行额外的代码时,请使用此选项
在模型中定义如下所示的列:
editing_date = db.Column(db.DateTime, onupdate=datetime.utcnow)