Creating a 21 character unique field for a model in Django
<p>I know the id is unique by itself, I want to create a unique field thats longer and less easy to guess. In short, this field will be a unique, 21 character alphanumeric string. I am doing this using this code below:</p>

<pre><code>class Organization(models.Model):
    name = models.CharField(max_length=255)
    key = models.CharField(max_length=21, unique=True, blank=True, null=True)

    def save(self, *args, **kwargs):
        if self.key == '' or self.key == None:
            key = ''
            for i in range(21):
                key += random.choice(string.lowercase + string.uppercase + string.digits)

            if Organization.objects.filter(key=key).exists():
                self.save() # Try again
            else:
                self.key = key
        super(Organization, self).save(*args, **kwargs)
</code></pre>

<p>In the <code>save</code> method, I do the following things:</p>

<ul>
<li>See if the object's key exists or not.</li>
<li>If not, I generate a 21 character key.</li>
<li>Then I check if an Organization with the key I generated exists or not.</li>
<li>If not, then the object's key is set to the generated one and saved.</li>
</ul>

<p><strong>Is this the right way to do this?</strong></p>

<p>Is there a better way with less code perhaps? Also, notice how my key field is unique, but also can be blank. Can that be an issue? So far, this has worked pretty well. Any help is appreciated.</p>