带有 auto_now_add 的 Django DateTimeField 要求默认

Art*_*sov 9 django

我的模型中有这个字段 created_at = models.DateTimeField( auto_now_add = True )

当我尝试进行迁移时,出现错误:

You are trying to add the field 'created_at' with 'auto_now_add=True' to user wi
thout a default; the database needs something to populate existing rows.

 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Run Code Online (Sandbox Code Playgroud)

我试图设置默认值,但它说default并且auto_now_add是互斥的。当然,我可以不使用默认值,auto_now_add但我想知道为什么会弹出这个错误。我错过了什么?

sha*_*fik 11

您已经有一些没有created_at价值的行。但是当您添加以下字段并运行迁移时

created_at = models.DateTimeField( auto_now_add = True)
Run Code Online (Sandbox Code Playgroud)

它期望现有行具有created_at价值。因此,它会在迁移时向您发出警告。

为了解决这个问题。您可以选择第一个选项,即Provide a one-off default now (will be set on all existing rows). 通过选择第一个选项,您是在寻求价值。在这里你可以输入timezone.now()。它将使用当前时间戳填充现有行。


小智 9

删除应用程序中的迁移文件,您可以在没有错误发生时执行迁移过程,它是由于先前创建的时间对象的原因而引发的。