auto_now 优先(显然,因为它每次都更新字段,而auto_now_add 仅在创建时更新)。这是DateField.pre_save方法的代码:
def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = datetime.date.today()
setattr(model_instance, self.attname, value)
return value
else:
return super().pre_save(model_instance, add)
如您所见,如果设置了auto_now 或同时设置了auto_now_add 并且对象是新的,则该字段将接收当天。
DateTimeField.pre_save 也一样:
def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = timezone.now()
setattr(model_instance, self.attname, value)
return value
else:
return super().pre_save(model_instance, add)