Search code examples
djangorestmodel

How can I generate a youtube style unique alphanumeric id model id in django


I want dont want to use the django id directly for viewsets in django, since that potentially reveals the number of items.
I already figured out how to generate UUIDs, which work, but are unwieldy and hexadecimal.
Is there a way to generate a guaranteed unique sufficently long alphanummeric string in django similar to a uuid?


Solution

  • You can probably do something like this (although untested):

    import random, string
    
    def random_id_field():
      rnd_id = ''.join(random.choices(string.ascii_letters + string.digits, k=16))
      return rnd_id
    
    class MyModel(models.Model):
      id = models.Charfield(max_length=16, unique=True, primary_key=True, default=random_id_field)
    

    Update

    In Python 3.6, they introduced the concept of secrets. Here is an example:

    from secrets import token_urlsafe
    random_string = token_urlsafe(16)
    print(random_string)
    

    Result: 'x3jFt0X_hZr2B4j6CexixQ'