id summary reporter owner description type status component version severity resolution keywords cc stage has_patch needs_docs needs_tests needs_better_patch easy ui_ux 28273 Document how to prevent adding columns with defaults in migrations Raphael Gaschignard Caio Ariede "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. " Cleanup/optimization closed Documentation 1.10 Normal fixed Accepted 1 0 0 0 0 0