urlhash = models.CharField(max_length=6, null=True, blank=True, unique=True)

def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def save(self):
    if not self.urlhash:
        self.urlhash = id_generator()
while MyModel.objects.filter(urlhash=self.urlhash).exists():
    self.urlhash = id_generator()
super(MyModel, self).save()
Generate unique id in django from a model field