0

I'm implementing this answer to add an automatic UUIDField to a database with existing rows.

The suggested adjustments to the data migration are:

from django_extensions.utils import uuid

def forwards(self, orm):
    for item in orm['mypp.myclass'].objects.all():
        if not item.uuid:
            item.uuid = uuid.uuid4() #creates a random GUID
            item.save()


def backwards(self, orm):
    for item in orm['mypp.myclass'].objects.all():
        if item.uuid:
            item.uuid = None
            item.save()

However, I don't want to allow blank=True to my model. How would I adjust the backwards() function in that case? The current item.uuid = None would no longer work...

Community
  • 1
  • 1
YPCrumble
  • 26,610
  • 23
  • 107
  • 172
  • `blank=True` doesn't mean you cannot do this `item.uuid = None`. It is `null=True` that prevents a field from being `None`. – yeh Dec 17 '15 at 23:27

1 Answers1

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():
        # [...]
Adrián
  • 6,135
  • 1
  • 27
  • 49