Random Primary Keys

(Originally posted July 15, 2013)

When you create an object in Django and save it, Django automatically assigns it a primary key (pk) to the object. This is the

There are two ways to do this in general.

One way to do this is to obfuscate the standard, auto-incrementing integer primary key values that Django’s model ORM provides out of the box. One way to do this method is to use something like AES encrypting that is provided up pycrypto. From there, you can create encrypt and decrypt methods that you wrap when you go to retrieve models from the database. Unfortunately, this method requires you remember to call this function every time you access an object. Hopefully you remember, and that would probably get really annoying.

The other method is to create a primary key yourself on object creation, and then use that throughout the app. To do this, you need to override the model’s save method which, when the object is first saved, will generate a random value to use as the primary key, check to see if there is something with the value previously assigned, and if not, use that as the value’s key.

The code is as follows:

def save(self*args, **kwargs):
    if not self.pk:
        while True:
            self.pk = int(str(uuid.uuid4().int)[0:6])
                super(Goal,self).save(*args, **kwargs)
            except IntegrityError:
        super(Goal,self).save(*args, **kwargs)

I prefer overriding the save method to generate a random id. It’s a one stop definition where you write the code once and don’t have to think about it again, which is always a good thing. Also, it allows you to get a very large number of objects just by changing the length of the slice you use to generate the key.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s