#28273: Have a way to prevent adding columns with defaults in migrations
-------------------------------------+-------------------------------------
Reporter: Raphael | Owner: nobody
Gaschignard |
Type: | Status: new
Uncategorized |
Component: Database | Version: 1.10
layer (models, ORM) |
Severity: Normal | Keywords:
Triage Stage: | Has patch: 0
Unreviewed |
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-------------------------------------+-------------------------------------
So normally the Django documentation says that it doesn't use database
defaults.
If you have a model where you add a {{{ NullBooleanField}}} with a model-
side default and generate a migration then you end up with the following
SQL being executed (at least for Postgres)
{{{
BEGIN;
--
-- Add field some_field to table
--
ALTER TABLE "appname_model" ADD COLUMN "some_field" boolean DEFAULT true
NULL;
ALTER TABLE "appname_model" ALTER COLUMN "some_field" DROP DEFAULT;
COMMIT;
}}}
This actually backfills the value for you in the DB during the ADD COLUMN
command
But from the PostgreSQL documentation:
> When a column is added with ADD COLUMN, all existing rows in the table
are initialized with the column's default value (NULL if no DEFAULT clause
is specified).
>Adding a column with a non-null default or changing the type of an
existing column will require the entire table and indexes to be rewritten.
So if you're adding a column to a big enough table, the migration run
itself will be very painful, because it will update _every_ row of your
table to set the default.
Usually you want to set the {{{default}}} value model-side to help with
the future backfill. So the way to handle this is to usually remove the
automatically inserted default from the migration. But it can be easy to
miss this (or to have custom fields that auto-set defaults).
But the generated SQL is something you basically never want to run on a
big table. I would love to have a way to just prevent a migration from
ever generating an ADD COLUMN with a DEFAULT clause.
I think there would be a way to handle this through simple changes in the
schema editor but I couldn't figure out how the default code was
generated.
--
Ticket URL: <https://code.djangoproject.com/ticket/28273>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/047.c820a972d179b727d86030b986144252%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.