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?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.