我想查看我的标题字段是否在保存方法中更改。以下是我到目前为止的情况:
class Answer(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
def save(self, *args, **kwargs):
if self.pk:
answer_prev = Answer.objects.get(pk=self.pk)
if answer_rev.title != self.title:
log.info('TITLE HAS CHANGED!!')
有更好的方法吗?
答案 0 :(得分:1)
我认为最好的解决方案是使用django model pre_save signal。
在保存之前,db中的实例仍然是原始实例,但实例参数具有新值,因此您可以检查字段是否已更改。
from django.db import models
from django.dispatch import receiver
@receiver(models.signals.pre_save, sender=Answer)
def prepare_save(sender, instance, **kwargs):
try:
current_instance = sender.objects.get(pk=instance.pk)
if current_instance.title != instance.title:
print 'Title changed to %s!' % instance.title
except sender.DoesNotExist:
print 'new answer. No title change'