Opened 6 years ago
Closed 6 years ago
#30390 closed Cleanup/optimization (wontfix)
makemigrations requires default when adding non-nullable field even when there are no rows.
Reported by: | Neil du Toit | Owned by: | Jay Welborn |
---|---|---|---|
Component: | Migrations | Version: | dev |
Severity: | Normal | Keywords: | makemigrations default null |
Cc: | Triage Stage: | Accepted | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | yes | UI/UX: | no |
Description
When adding a non-nullable field to a model, and then running
python manage.py makemigrations <appname>
Django will respond with the following:
"You are trying to add a non-nullable field <field> to <model> without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: "
This is quite frustrating when there are no existing rows. It requires more effort and, more importantly, leads to confusion about what migrations are doing. I frequently go back and check the database for my own sanity after seeing this message.
Desired behavior:
If there are no rows then there is no need for a default. This message should not be displayed and the migration should simply be run.
Change History (4)
comment:1 by , 6 years ago
comment:2 by , 6 years ago
Triage Stage: | Unreviewed → Accepted |
---|
comment:3 by , 6 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
If the community wants this change, I have a preliminary patch working that will need tests/review.
comment:4 by , 6 years ago
Resolution: | → wontfix |
---|---|
Status: | assigned → closed |
Version: | 2.2 → master |
Thanks for the report, however this is expected behavior. makemigrations
cannot be based on the number of rows in the current database because in most of cases you will prepare migrations on one environment (e.g. dev or test) and run them on another (e.g. other dev, test, live etc.). Moreover even on the same db the number of rows can change between preparing migrations and running them.
I have recreated this behavior. I'm not sure if there is a reason behind empty tables getting the same warning as populated tables.
If this is a desired change, I can write a patch that drops the warning when adding a field to an empty database table.