[Fixed]-Django datetime default value in migrations

26👍

auto_now_add set the current datetime when the instance is created, which never happens during your migration so you are trying to leave NULL a non-nullable field.

The solution would be to add a default date to your model, makemigrations, then remove the default parameter from the model, makemigrations again and finally migrate. You can achieve the same adding null=True to the field, adding a RunPython or RunSQL to your migration that populates the field, and then remove the null=true from the field.

At the end you can merge both migration files (or simple write it yourself) to end with something like:

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),
    ),
]

I just wrote it so I hope it does not have many typos

Leave a comment