Clyde Mulenga
Clyde Mulenga

Reputation: 77

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

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?

Upvotes: 1

Views: 1415

Answers (2)

Alicklaz
Alicklaz

Reputation: 79

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).

Upvotes: 0

Reza Heydari
Reza Heydari

Reputation: 1211

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)

Upvotes: 3

Related Questions