About Populating New Mandatory Fields in Migrations

When you create a new mandatory slug field, its values won't exist for the old entries.

While making migrations and asked for the default value, set it to an empty string or None temporarily, and then modify the migration:

from django.db import migrations, models

def populate_slug(apps, schema_editor):
    from django.utils.text import slugify

    Post = apps.get_model("blog", "Post")
    for post in Post.objects.all():
        post.slug = slugify(post.title)
        post.save(update_fields=["slug"])

class Migration(migrations.Migration):
    dependencies = [
        ("blog", "0001_initial"),
    ]

    operations = [
        # Add the `slug` field with `blank=True`
        migrations.AddField(
            model_name="post",
            name="slug",
            field=models.SlugField(blank=True, max_length=255, verbose_name="Slug"),
            preserve_default=False,
        ),

        # Populate `slug` values
        migrations.RunPython(populate_slug, migrations.RunPython.noop),

        # Remove `blank=True`
        migrations.AlterField(
            model_name="post",
            name="slug",
            field=models.SlugField(max_length=255, verbose_name="Slug"),
            preserve_default=False,
        ),
    ]

Tips and Tricks Programming Databases Django 5.x Django 4.2 Django 3.2