auto_now和auto_now_add之间的区别
问题描述:
我在 Django
模型字段中了解的是
What I understood in Django
models field's attributes is
-
auto_now
-每次调用Model.save()时,将字段的值更新为当前时间和日期. -
auto_now_add
-使用记录创建的时间和日期更新值.
-
auto_now
- updates the value of field to current time and date every time the Model.save() is called. -
auto_now_add
- updates the value with the time and date of creation of record.
我的问题是,如果模型中的文件同时包含设置为True的 auto_now
和 auto_now_add
,该怎么办?在这种情况下会发生什么?
My question is what if a filed in model contains both the auto_now
and auto_now_add
set to True? What happens in that case?
答
auto_now
优先(显然,因为它每次都会更新字段,而 auto_now_add
仅在创建时更新).这是 DateField.pre_save
方法:
auto_now
takes precedence (obviously, because it updates field each time, while auto_now_add
updates on creation only). Here is the code for DateField.pre_save
method:
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
且对象是新对象,则该字段将接收当天的日期.
As you can see, if auto_now
is set or both auto_now_add
is set and the object is new, the field will receive current day.
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)