8

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?

Charles Haro
  • 1,866
  • 3
  • 22
  • 36

2 Answers2

5

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.

Ashique PS
  • 691
  • 1
  • 12
  • 26
1

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

Andrey Shipilov
  • 1,986
  • 12
  • 14
  • Im not worried about the uuid field id because of this post, I want the random 8 letter code to be safe. Which django-uuidfield wont do for me. http://stackoverflow.com/questions/703035/when-are-you-truly-forced-to-use-uuid-as-part-of-the-design/786541#786541 – Charles Haro May 29 '15 at 17:21