Adding a UUID Field to an Existing Django Model
It’s not immediately obvious how to add a UUID field to an existing Django model. Let’s say you have a database with some data in it about certain accounts, but you realize you need a way of obfuscating the pk of a model instance. UUID is a perfect candidate and a pretty popular implementation for Django comes from dcramer called django-uuidfield. Everything is fine and dandy until you try to add that field to an existing model that already has data, then try to auto migrate it using south.
How to add a UUID field to an existing model
The problem here is that we need to add a UUID value to all existing records, not just new ones. Peaking through the source code you will see what uuid method they are using and what the data should look like.
- Add the UUID field to your model with blank=True, null=True, max_length=32, auto=True in models.py.
- Run the schemamigration command with south and then open up the resulting migration file.
- Edit your migration file with the following:
# You'll need to import the following import uuid # At the end of the forwards() function add the following def forwards(self, orm): ... for a in MyModel.objects.all(): a.uuid = u'' + str(uuid.uuid1().hex) a.save()
That will loop through all the existing instances of that model in your database and add a uuid to it as part of the migration. Make sure you test it first!