Skip to content

Instantly share code, notes, and snippets.

@BigglesZX
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BigglesZX/366fcc47535763ab4d1e to your computer and use it in GitHub Desktop.
Save BigglesZX/366fcc47535763ab4d1e to your computer and use it in GitHub Desktop.
Generate a unique code for an instance of a Django model on save
"""
This uses the DB to ensure uniqueness of the code. Better than checking separately
with the DB and then saving, which introduces a race condition.
"""
class UserProfile(BaseModel):
code = models.CharField(max_length=4,
db_index=True,
unique=True)
def generate_code(self):
""" Pick from 0-9, a-z EXCEPT O (capital o) because mistakes """
self.code = ''.join(random.choice('0123456789ABCDEFGHIJKLMNPQRSTU'
'VWXYZ') for i in range(4))
return self
def save(self, *args, **kwargs):
""" Generate a unique code on first save """
if not self.pk and not self.code:
while True:
try:
self.generate_code()
super(UserProfile, self).save(*args, **kwargs)
except IntegrityError:
continue
else:
break
else:
super(UserProfile, self).save(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment