Last active
August 29, 2015 14:10
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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