Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model fields unique=True and default=function

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?

like image 919
Charles Haro Avatar asked May 29 '15 03:05

Charles Haro


2 Answers

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

like image 29
Andrey Shipilov Avatar answered Nov 23 '22 21:11

Andrey Shipilov


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.

like image 106
Ashique PS Avatar answered Nov 23 '22 22:11

Ashique PS