Question

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?

Was it helpful?

Solution

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')
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top