Skip to content

Instantly share code, notes, and snippets.

@hwshim0810
Created March 6, 2018 04:11
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 hwshim0810/e3d6d005e9b93002feac8b32a559a4cd to your computer and use it in GitHub Desktop.
Save hwshim0810/e3d6d005e9b93002feac8b32a559a4cd to your computer and use it in GitHub Desktop.
Generate unique key with django model
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