Created
March 6, 2018 04:11
-
-
Save hwshim0810/e3d6d005e9b93002feac8b32a559a4cd to your computer and use it in GitHub Desktop.
Generate unique key with django model
This file contains 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
import string | |
from random import SystemRandom | |
def generate_key(field_name, model, size=8): | |
charset = string.ascii_lowercase + string.digits | |
key = ''.join(SystemRandom().choice(charset) for _ in range(size)) | |
is_exist = model._default_manager.filter(**{field_name: key}).exists() | |
while is_exist: | |
key = generate_key(size, model) | |
return key |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment