-8

This question already has answers here: How to create a GUID/UUID in Python (8 answers) Your post has been associated with a similar question. If this question doesn’t resolve your question, ask a new one.

Closed 8 mins ago.

(Private feedback for you)

I am generating a string using below technique but one thing I just want be sure of is that uniqueness of the string. will be a great help if anybody evaluate and suggest if there is a better way of getting a unique string.

models.py
import random
import string

def random_string_generator(size=10, chars=string.digits):
    return ''.join(random.choice(chars) for _ in range(13))

class Orders(models.Model):
    id= models.AutoField(primary_key=True)
    token = models.CharField(max_length=13,
            default=random_string_generator,
            editable=False,
            unique=True)
    
    identifier = models.CharField(max_length=13,
                       default=random_string_generator,
                       editable=False,
                       unique=True)
0

1 Answer 1

0

The function can be made to check if any object has the same string and you can use a loop to do so. Something like this:

def random_string_generator(size=10, chars=string.digits):
    while True:
        string = ''.join(random.choice(chars) for _ in range(13))
        if (Orders.objects.filter(token=string).count() == 0 and Orders.objects.filter(identifier=string).count() == 0:
            break
    return string
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.