我有一个模特,像这样:
name = models.CharField(max_length=255)
modify_time = models.DateTimeField(auto_now=True)
chasha = models.CharField(max_length=255)
stat = models.CharField(max_length=255)
通常,' modify_time'将在我更新名称',' chasha',' stat'时更新领域。但是,我只是不想要' modify_time'我更新了' stat'时已更新。我怎么能这样做?
感谢。
答案 0 :(得分:1)
使用自定义保存方法通过查看上一个实例来更新字段。
from django.db import models
from django.utils import timezone as tz
class MyModel(models.Model):
name = models.CharField(max_length=255)
modify_time = models.DateTimeField(null=True, blank=True)
chasha = models.CharField(max_length=255)
stat = models.CharField(max_length=255)
def save(self, *args, **kwargs):
if self.pk: # object already exists in db
old_model = MyModel.objects.get(pk=self.pk)
for i in ('name', 'chasha'): # check for name or chasha changes
if getattr(old_model, i, None) != getattr(self, i, None):
self.modify_time = tz.now() # assign modify_time
else:
modify_time = tz.now() # if new save, write modify_time
super(MyModel, self).save(*args, **kwargs) # call the inherited save method
修改:如上所述从auto_now
删除modify_time
,否则将在保存方法中设置。