Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django datetime default value in migrations

I've read some questions about this issue in so, also this question is not giving the correct answer for my case:

I'm adding a created_time field in my already existing models, so no date in the mysql table belonging to the model.

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

I apply the migration using python manage.py makemigrations

And I get this error:

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:

I tryed many options:

creation_date = models.DateTimeField(auto_now_add=True)

This one is giving the same error.

How can this migration be achieved, if USE_TZ in settings is set to False?
Btw, is this a bug in Django 1.9.4 makemigrations script?

like image 673
Evhz Avatar asked May 31 '16 08:05

Evhz


1 Answers

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

like image 55
dnaranjo Avatar answered Oct 21 '22 16:10

dnaranjo