ID Alfanumerico Django

0

good:

I'm trying to generate unique ID's with letters and numbers but all the methods I've tried return strings that can give the possibility of repeating and cause the application to fail. Right now I have this:

class Comentario(models.Model):
    id = models.CharField(primary_key=True, max_length=9, default=token_generator.make_token(), editable=False)
    perfil = models.ForeignKey(Perfil)
    comentario = models.CharField(max_length = 255)
    producto = models.ForeignKey(Producto, related_name='comentarios',on_delete=models.CASCADE)
    fecha = models.DateTimeField(auto_now_add = True)

and the next class that randomly generates strings:

class RandomTokenGenerator(object):
    def __init__(self, chars=None, random_generator=None):
        self.chars = chars or string.ascii_uppercase + string.ascii_lowercase + string.digits
        self.random_generator = random_generator or random.SystemRandom()

    def make_token(self, n=9):
        return ''.join(self.random_generator.choice(self.chars) for _ in range(n))

token_generator = RandomTokenGenerator()

I need 9 digits, that's why the UUID generated by django does not work for me

    
asked by F Delgado 26.01.2018 в 17:06
source

1 answer

1

I suggest you use a function instead of a class for this type of options

def random_id(lenght=9);
    return ''.join(random.choice(string.letters + string.digits) for x in range(lenght))

and in your model to pass the object function not the function itself

class Comentario(models.Model):
    id = models.CharField(primary_key=True, max_length=9, default=random_id, editable=False)
    perfil = models.ForeignKey(Perfil)
    comentario = models.CharField(max_length = 255)
    producto = models.ForeignKey(Producto, related_name='comentarios',on_delete=models.CASCADE)
    fecha = models.DateTimeField(auto_now_add = True)

I hope it serves you

    
answered by 26.01.2018 / 18:17
source