两种方法检查模型中某个字段发生改变
How to check if a filed has changed when model save
Django 2.1.7
1. 在模型中检查
适用于在任何时候字段发生变化采取动作
class Task(models.Model):
if_done = models.BooleanField('If Done', default=False)
__original_done = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# inital original
self.__original_done = self.if_done
def save(self, *args, **kwargs):
if not self.__original_done and self.if_done:
# if_done changed, do something
super().save(*args, **kwargs)
# update the original
self.__original_done = self.if_done
2. 在 Admin Class 中检查
适用于只在使用admin的时候检查字段变化,
由于写在了admin class 里,所以如果有其他views 修改了改model,检查是不起作用的。
利用 Form.changed_data
值检查
class TaskAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if 'if_done' in form.changed_data:
messages.info(request, "The task status has changed")
else:
messages.info(request, "The task status has not changed")
super().save_model(request, obj, form, change)