Python random character string repeated 7/2000 records
Question: I am using the below to generate a random set of characters and numbers:

    
    
    tag = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(36)])
    

I thought that this was a decent method. 36 character length, with each
character being one of 36 unique options. Should be a good amount of
randomness, right?

Then, I was running a query off an instance with what I thought was a unique
`tag`. Turns out, there were **SEVEN (7)** records with the same "random"
`tag`. So, I opened the DB, and ran a query to see the repeatability of my
tags.

Turns out that not only does mine show up 7 times, but there are a number of
tags that repeatedly appear over and over again. With approximately 2000 rows,
it clearly should not be happening.

Two questions:

**(1) What is wrong with my approach, and why would it be repeating the
same`tag` so often?**

**(2) What would be a better approach to get unique tags for each record?**

Here is the code I am using to save this to the DB. While it is written in
Django, clearly this is not a django related question.

    
    
    class Note(models.Model):
        ...
        def save(self, *args, **kwargs):
            import random
            import string
            self.tag = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(36)])
            super(Note, self).save(*args, **kwargs)
    


Answer: The problem with your approach:

  1. true randomness/crypto is hard, you should try to use tested existing solutions instead of implementing your own.
  2. Randomness isn't guaranteed - while 'unlikely', there's nothing preventing the same string to be generated more than once.

A better solution would be to not reinvent the wheel, and use the
[uuid](https://docs.python.org/2/library/uuid.html) module, a common solution
to generating unique identifiers:

    
    
    import uuid
    
    tag = uuid.uuid1()
    

