Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python “立即自动”和“立即自动添加”之间的区别_Python_Django_Django Models_Django Forms_Django Templates - Fatal编程技术网

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字段的属性中理解的是

  • 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
仅在创建时更新)。以下是方法的代码:

如您所见,如果设置了
auto\u now
,或者同时设置了
auto\u now\u add
,并且对象是新的,则该字段将接收当前日期

同样适用于:


根据说明,使用but
auto\u now
auto\u now\u添加
as
True
将导致错误,因为它们都是互斥的。

正如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)