Creating custom unique Id for new record but having duplicate error

Viewed 123

creating an id and trying to insert a record with it, but having duplication error.

django.db.utils.IntegrityError: (1062, "1062 (23000): Duplicate entry '715683160' for key 'projects_project.PRIMARY'", '23000')

import random


def makeUniqueLongId():
  return random.randint(100000000, 999999999)


class Project(models.Model):
  id = models.BigIntegerField(unique=True, primary_key=True, default=makeUniqueLongId(), editable=False)
  ...

How can I prevent id duplication? Is unique=True not enough to return new id with makeUniqueLongId()

1 Answers

Your code does not create a unique ID, but just a random one. The more often you run makeUniqueLongId() the higher is the probability that you will eventually get a duplicate ID.

Django's unique=True will prevent that an entry will be saved if its value already exists and that's exactly why you're getting the error (see documentation here). Moreover, since you are setting primary_key = True, there is no need for unique, because that condition will be set automatically.

Try adding a custom save() method to your model:

def makeUniqueLongId():
  return random.randint(100000000, 999999999)

class Project(models.Model):
  id = models.BigIntegerField(primary_key=True, editable=False)
  ...

# while id is not yet set, create new random id. If random id not already exists, save as new id.

    def save(self, *args, **kwargs):
        while not self.id:
            new_id = makeUniqueLongId()
        if not type(self).objects.filter(id=new_id).exists():
            self.id = new_id
        super().save(*args, **kwargs)
Related