Django 1.8 Migrations. Adding DateTimeField after db creation. Best practices?
I've just had the exact problem. I use Django 1.10. I read Kevin answer and I've tried to put default value when Django asked me to fill it as datetime.now
string.
And I was surprised because, for those fields, Django automatically ask you if you want to use datetime.now
as default:
$ ./manage.py makemigrations
You are trying to add the field 'date_created' with 'auto_now_add=True' to projectasset without 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
Select an option: 1
Please enter the default value now, as valid Python
You can accept the default 'timezone.now' by pressing 'Enter' or you can provide another value.
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
[default: timezone.now] >>>
So, I just confirm that and everything seems to be working fine!
I think the best practice here would have been to make the fields nullable. What your created
field means at the moment is: "The time when the instance was created, or the arbitrary time when I ran the migration." The standard way to represent the lack of a value is NULL
, rather than an arbitrary value.
That said, if you do want to use some arbitrary value you just need to tell Django what it is. Usually makemigrations
gives you the option to indicate a one-off value to use for existing rows - did that not happen?
A more laborious method would be to declare the field nullable, then create a data migration to fill in your desired value, and then make it non-nullable. What you did is basically a simplified version of that. I don't see it creating any problems moving forward other than the issue of created
not really being the time the instance was created.