django-add-default-value is a Django Migration Operation that facilitates transferring a field's default value directly to the database schema. This addresses Django's default behavior of handling `default` values at the application level and dropping the database `DEFAULT` constraint after initial row population. The library is currently active, with version 0.10.0 released in February 2022, and helps ensure database-level default constraints persist for improved data integrity and compatibility with non-Django database access.
pip install django-add-default-valueVerified import paths — ran on the pinned version, not inferred.
To use `django-add-default-value`, manually add the `AddDefaultValue` operation to an autogenerated migration file immediately after an `AddField` operation. This ensures that the specified default value for the field is transferred to the database schema, maintaining the default constraint at the database level.
Use `django-add-default-value.AddDefaultValue` in your migrations for critical fields to ensure the database schema itself enforces the default, or leverage Django's `db_default` option (available in Django 4.2+).
To establish a persistent database default, either add `default='some_value'` to your model field and then use `AddDefaultValue` in the migration, or, for simple static defaults, define `db_default` directly on the field (Django 4.2+).
For callable defaults, `django-add-default-value` might not be the direct solution for dynamic database defaults (as SQL defaults are often static). Consider if a database-level default is truly required, or if application-level enforcement is sufficient. If a static default based on the callable's *initial* value is acceptable for the database, `AddDefaultValue` can be used with that static value.
Edit your generated migration file to include `AddDefaultValue(model_name='...', name='...', value='...')` after `migrations.AddField`. Alternatively, add `default='some_value'` to the field definition in `models.py` before `makemigrations` and then include `AddDefaultValue`.
Ensure `AddDefaultValue` is used in the migration that adds the non-nullable field. This establishes a `DEFAULT` constraint at the database level, preventing `NOT NULL` violations when no value is explicitly provided. Run `python manage.py migrate` to apply the migration.
Run `pip install django-add-default-value` to install the library. Verify the import statement is `from django_add_default_value import AddDefaultValue`.