[Fixed]-How do I structure the `backwards` function in a Django migration without allowing null values in the database?

1👍

You have to do the migration in 3 steps:

  1. Add your UUIDField with null=True so existing rows do not break the constraint.

  2. Create a data migration to fill the uuids of existing rows similar to your current code.

  3. Add another migration with the NOT NULL constraint by removing the null=True from your field declaration.

PS: Your code is for the outdated South migrations. The current equivalent for django-migrations would be:

def forwards(apps, schema_editor):
    MyClass = apps.get_model('myapp', 'MyClass')
    for item in MyClass.objects.all():
        # [...]

Leave a comment