How can I make the get_random_string Django module to return only numerical values?

Question:

What should I do to my simple code below, so that it only returns numerical values?

>>> from django.utils.crypto import get_random_string
>>> get_random_string(10)
>>> 'PhaWT9X02U'

Something like: 1067603657
And if it is possible, can you recommend an id field generated in this manner?

Asked By: Clyde Mulenga

||

Answers:

Add allowed_chars

get_random_string(10, allowed_chars='0123456789')

And to use as id:

def random_id():
   random_str = get_random_string(10, allowed_chars='0123456789')
   return int(random_str)

And add id field to your model like that:

id = models.IntegerField(primary_key=True, default=random_id, editable=False)
Answered By: Reza Heydari

We can extend Reeza’s solution by adding a uniqueness constraint to to the field to enable unique behaviour of the ID and by making the generator function aware of database state.

def random_id():    
   random_int = int(get_random_string(10, allowed_chars='0123456789'))
   while YourModel.objects.filter(id=random_int).exists():       
      random_int = int(get_random_string(10, allowed_chars='0123456789'))    
   return random_int 

and then

id = models.IntegerField(primary_key=True, default=random_id, editable=False, unique=True) 

The performance trade-off is minimal for most cases as chances of a collision is minimal and so this function will not be run more than once (there are 10^10 possibilities for this ID).

Answered By: Alicklaz
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.