Python “立即自动”和“立即自动添加”之间的区别
我在Python “立即自动”和“立即自动添加”之间的区别,python,django,django-models,django-forms,django-templates,Python,Django,Django Models,Django Forms,Django Templates,我在Djangomodels字段的属性中理解的是 auto\u now-每次调用Model.save()时,将字段值更新为当前时间和日期 auto\u now\u add-使用创建记录的时间和日期更新值 我的问题是,如果一个归档模型同时包含auto\u now和auto\u now\u add设置为True,该怎么办?在这种情况下会发生什么?auto\u now优先(显然,因为它每次都更新字段,而auto\u now\u add仅在创建时更新)。以下是方法的代码: 如您所见,如果设置了aut
Django
models字段的属性中理解的是
-每次调用Model.save()时,将字段值更新为当前时间和日期auto\u now
-使用创建记录的时间和日期更新值auto\u now\u add
我的问题是,如果一个归档模型同时包含
auto\u now
和auto\u now\u add
设置为True,该怎么办?在这种情况下会发生什么?auto\u now
优先(显然,因为它每次都更新字段,而auto\u now\u add
仅在创建时更新)。以下是方法的代码:
如您所见,如果设置了auto\u now
,或者同时设置了auto\u now\u add
,并且对象是新的,则该字段将接收当前日期
同样适用于:
根据说明,使用but
auto\u now
和auto\u now\u添加asTrue
将导致错误,因为它们都是互斥的。正如Django官方文档所述-
立即自动
,auto\u now\u add
和default
是互斥的,如果一起使用会导致错误这些字段被内置到Django中,明确地用于此目的-auto\u now字段在每次保存对象时都会更新为当前时间戳,因此非常适合在上次修改对象时进行跟踪,当一行首次添加到数据库时,自动添加字段保存为当前时间戳,因此非常适合在创建行时进行跟踪
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)
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)