auto_now 和 auto_now_add 的区别 [英] Difference between auto_now and 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<的代码/code>
方法:
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)
这篇关于auto_now 和 auto_now_add 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!