我一直在Google和StackOverflow上进行搜索。基本上,我想尝试覆盖Flask-Admin上的删除功能,以实际上不删除记录,而是更新对象的行“ deleted_by”和“ deleted_on”。
我在StackOverflow上发现了几个问题,这些问题解释了如何通过使用on_model_change来更改保存按钮上的逻辑,但是没有一个关于删除模型逻辑的具体问题。我也没有在文档中找到与此有关的任何信息。谁能告诉我该如何处理这个问题?
谢谢!
答案 0 :(得分:1)
您视图中的覆盖方法delete_model
。如果您使用的是Sqlalchemy视图,则为default behaviour,请注意在self.session.delete(model)
块中对try ... except
的调用。
def delete_model(self, model):
"""
Delete model.
:param model:
Model to delete
"""
try:
self.on_model_delete(model)
self.session.flush()
self.session.delete(model)
self.session.commit()
except Exception as ex:
if not self.handle_view_exception(ex):
flash(gettext('Failed to delete record. %(error)s', error=str(ex)), 'error')
log.exception('Failed to delete record.')
self.session.rollback()
return False
else:
self.after_model_delete(model)
return True
您需要在视图中添加以下内容:
class MyModelView(ModelView):
def delete_model(self, model):
"""
Delete model.
:param model:
Model to delete
"""
try:
self.on_model_delete(model)
# Add your custom logic here and don't forget to commit any changes e.g.
# self.session.commit()
except Exception as ex:
if not self.handle_view_exception(ex):
flash(gettext('Failed to delete record. %(error)s', error=str(ex)), 'error')
log.exception('Failed to delete record.')
self.session.rollback()
return False
else:
self.after_model_delete(model)
return True
此外,您可能不想打扰self.on_model_delete(model)
和self.after_model_delete(model)
调用,因为默认情况下它们什么都不做。