So I have a model that looks like this
def create_invite_code():
return str(uuid.uuid4())[0:8]
class InviteCodes(models.Model):
id = models.CharField(max_length = 36, primary_key = True, default=build_uuid)
code = models.CharField(max_length=8, unique=True, default=create_invite_code)
What happens if create_invite_code returns a code that already exists in the db, will django call the function again until it finds one that doesn't exist? Or will it error out?
As people said here, it will raise "UNIQUE constraint failed" integrity error. Which could potentially happen cause you're not doing any check for uniqueness.
I would recommend django-uuidfield by David Cramer. It handles all the validation for you.
https://github.com/dcramer/django-uuidfield
The code field in your model InviteCodes
is a unique field. If you tries to create another entry with an already existing code, then python will raise IntegrityError: UNIQUE constraint failed
exception.
You can test it by returning a constant string from create_invite_code
function. For example,
def create_invite_code():
return 'test'
The first entry will be unique, but in the second call the exception will be raised.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With