I've added a UUID field to some of my models and then migrated with South. Any new objects I create have the UUID field populated correctly. However the UUID fields on all my older data is null.
Is there any way to populate UUID data for existing data?
To add UUID values to all existing records first you will need to make sure your model has the UUID filed with
blank=True, null=True
Then Run the schemamigration command with south and then open up the resulting migration file. And then Edit your migration file with the following as shown in this post
Quote:
As stated that will loop through existing instances and add a uuid to it as part of the migration.
For the following sample class:
If you're using South, create a data migration:
And then use the following code to update the migration with the specific logic to add a UUID:
You can create different types of UUIDs, each generated differently. the uuid.py module in Django-extensions has the complete list of the types of UUIDs you can create.
It's important to note that if you run this migration in an environment with a lot of objects, it has the potential to time out (for instance, if using fabric to deploy). An alternative method of filling in already existing fields will be required for production environments.
It's possible to run out of memory while trying to do this to a large number of objects (we found ourselves running out of memory and having the deployment fail with 17,000+ objects).
To get around this, you need to create a custom iterator in your migration (or stick it where it's really useful, and refer to it in your migration). It would look something like this:
And then your migrations would change to look like this:
There is now an excellent, updated answer for Django 1.9 to this exact question in the Django docs.
Saved me a lot of time!