Created
January 22, 2020 06:54
-
-
Save 0ex-d/68b861faacbf9fe2ca916da2b11e9e09 to your computer and use it in GitHub Desktop.
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
# 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