迁移中的 Django 日期时间默认值

Django datetime default value in migrations

我在 so 中阅读了一些关于这个问题的问题,this 问题是没有 为我的案例给出正确答案:

我正在我现有的模型中添加一个 created_time 字段,因此属于该模型的 mysql table 中没有日期。

class Configs(models.Model):
    ...
    creation_date = models.DateTimeField(auto_now_add=True, blank=True)
    ...

我使用 python manage.py makemigrations

应用迁移

我得到这个错误:

You are trying to add a non-nullable field 'creation_date' to collections without a default; we can't do that (the database needs something to populate existing rows). Please select a fix:

我尝试了很多选择:

creation_date = models.DateTimeField(auto_now_add=True)

这个给出了同样的错误。

如果设置中的 USE_TZ 设置为 False,如何实现此迁移?
顺便说一句,这是 Django 1.9.4 makemigrations 脚本中的错误吗?

auto_now_add 在创建实例时设置当前日期时间,这在您的迁移过程中永远不会发生,因此您试图留下 NULL 一个不可为 null 的字段。

解决方案是向模型添加默认日期 makemigrations,然后从模型中删除默认参数,再次 makemigrations,最后 migrate。您可以将 null=True 添加到该字段,将 RunPython or RunSQL 添加到填充该字段的迁移,然后从该字段中删除 null=true

最后你可以合并两个迁移文件(或者简单地自己写)以这样的结尾:

operations = [
    migrations.AddField(
        model_name='configs',
        name='creation_date',
        field=models.DateTimeField(auto_now_add=True, null=True, blank=True),
    ),
   migrations.RunPython(populate_dates),
   migrations.AlterField(
        model_name='configs',
        name='creation_date',
        field=models.DateTimeField(auto_now_add=True, blank=True),
    ),
]

刚刚写的,希望别有很多错别字