Generating Random IDs for Django Model Objects With Custom Save Method

For one project, I needed to create random, unique primary keys for model objects in Django. I ended up utilizing and modifying the code from the this Stack Exchange answer to get it to work:

def save(self, *args, **kwargs):
    """
    Object Primary Key IDs are based on the two different attributes from the object: TYPE and SIDE attributes.

    TYPE1: K#####[]
    TYPE2: U#####[]
    TYPE3: H#####[]
    TYPE4: S#####[]

    # = Random five digit number with values 0-9

    [] = 'R' or 'L' depending on side attirbute.

    * All letters are upper-case.
    """
    while not self.object_id:
        ret = []
        if self.type == self.TYPE_CHOICE_K:
            ret.append('K')
        elif self.type == self.TYPE_CHOICE_U:
            ret.append('U')
        elif self.type == self.TYPE_CHOICE_H:
            ret.append('H')
        elif self.type == self.TYPE_CHOICE_S:
            ret.append('S')

        ret.extend(random.sample(string.digits, 5))
        ret.append(self.side)

        newid = ''.join(ret)

        if Object.objects.filter(pk=newid).count() == 0:
            self.object_id = newid

The crux of this is that we create an ID only if the object does not have the custom ID. At the end of the random ID generation, we check to see if any objects exist with that ID. If that key is already in use, we make another one. And we repeat that until we have a unique ID.

← Return Home