0

I'm using the following code to generate a UUID for every new instance of a model object:

def make_uuid(type):
    """Takes an entity type identifier string as input and returns a hex of UUID2 with a 
    type identifier pre-pended for readability"""

    return str(type)+str(uuid.uuid1().hex)

Model field:

account_uuid = models.CharField(max_length=34, default=make_uuid('AC'), db_index=True, unique=True)

When I actually run the app, the first attempt works great, but the second and all subsequent attempts fail with the following message:

Exception Type: IntegrityError

Exception Value: duplicate key value violates unique constraint "accounts_accounts_account_uuid_key"

Any ideas as to what might be going on?

Sologoub
  • 5,312
  • 6
  • 37
  • 65
  • Edit `unique=True` to `null=True` http://stackoverflow.com/questions/30927563/django-1-8-default-option-only-executes-external-function-once#answer-30927966 – Chemical Programmer Jan 16 '16 at 07:52

1 Answers1

0

You are passing the result of a make_uuid call instead of a callable object to default.

Your code equals the code below.

default_uuid = make_uuid('AC')
account_uuid = models.CharField(max_length=34, default=default_uuid, db_index=True, unique=True)

Field.default:

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

You can use partial or lambda to generate a new uuid function.

from functools import partial
account_uuid = models.CharField(
    max_length=34, 
    default=partial(make_uuid,'AC')
)
Leonardo.Z
  • 9,425
  • 3
  • 35
  • 38
  • Thank you! Works perfectly... but feels like a hack... I can't quite put my finger on it, but it feels like a workaround to a straightforward mistake I am making else where. – Sologoub Nov 14 '13 at 06:41