Alex Kehayias's Blog

  • Archive
  • RSS

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.

  1. Add the UUID field to your model with blank=True, null=True, max_length=32, auto=True in models.py.
  2. Run the schemamigration command with south and then open up the resulting migration file. 
  3. 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!

    • #django
    • #uuid
    • #python
  • 1 year ago
  • 1
  • Permalink
  • Share
    Tweet

1 Notes/ Hide

  1. e-mechanism likes this
  2. alexkehayias posted this
← Previous • Next →

About

Blogging about hacking code, life, and music.

Me, Elsewhere

  • @alexkehayias on Twitter
  • Facebook Profile
  • Linkedin Profile

Twitter

loading tweets…

I Dig These Posts

  • Post via jordanorelli
    hexes

    image

    source

    Post via jordanorelli
  • Photoset via ruineshumaines

    Katharina Grosse

    Photoset via ruineshumaines
  • Photoset via myedol

    Imeüble by Bjørn Jørund Blikstad

    Created out of plastic this interesting shelving system really messes with your mind. Simple to assemble and...

    Photoset via myedol
  • Photo via tr3ats

    There’s a sense of satisfaction when using a pen ‘til it runs out of ink. It doesn’t happen often, but when it does, it feels like the arrival of a...

    Photo via tr3ats
See more →
  • RSS
  • Random
  • Archive
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr