Skip to content

Instantly share code, notes, and snippets.

@0ex-d
Created January 22, 2020 06:54
Show Gist options
  • Save 0ex-d/68b861faacbf9fe2ca916da2b11e9e09 to your computer and use it in GitHub Desktop.
Save 0ex-d/68b861faacbf9fe2ca916da2b11e9e09 to your computer and use it in GitHub Desktop.
# Method 1
def create_obj():
id = ''.join(random.choices(string.digits, k=8))
try:
MyModel.objects.save(id=id)
except IntegrityError:
create_obj()
# Method 2
def create_unique_id():
return ''.join(random.choices(string.digits, k=8))
def create_object():
id = create_unique_id()
unique = False
while not unique:
if not MyModel.objects.get(pk=id):
unique = True
else:
id = create_unique_id()
MyModel.objects.save(id=id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment