pythoncassandracqlengine

cqlengine model default values and uuid


Working with cqlengine models i have found an unexpected behaviour with default_values and uuid.

I am using python 3.4, and cqlengine from cassandra-driver 2.5.0.

with following code:

from cassandra.cqlengine import columns, connection, management
from cassandra.cqlengine.models import Model

import uuid

class Person(Model):
    id = columns.UUID(primary_key=True, default=uuid.uuid4())
    first_name  = columns.Text()
    last_name = columns.Text()

connection.setup(['127.0.0.1'], 'test_keyspace', 1, protocol_version=2)
management.sync_table(Person)

print("default value")
for i in range(10):
    p = Person().save()
    print(p.id)


print("\nparameter value")
for i in range(10):
    p = Person(id=uuid.uuid4()).save()
    print(p.id)

get output:

default value
703ddd0a-5a36-4c07-975b-638a9f7d2404
703ddd0a-5a36-4c07-975b-638a9f7d2404
703ddd0a-5a36-4c07-975b-638a9f7d2404
703ddd0a-5a36-4c07-975b-638a9f7d2404
703ddd0a-5a36-4c07-975b-638a9f7d2404
703ddd0a-5a36-4c07-975b-638a9f7d2404
703ddd0a-5a36-4c07-975b-638a9f7d2404
703ddd0a-5a36-4c07-975b-638a9f7d2404
703ddd0a-5a36-4c07-975b-638a9f7d2404
703ddd0a-5a36-4c07-975b-638a9f7d2404

parameter value
1366251d-36fc-480e-abae-bbbd957035af
e0f6936d-08d9-4308-bb68-79ba8d8db162
2cbcf896-96ec-4d29-993f-84336a13a3b5
2b0c765e-6cd8-4da0-86e5-14f49f5fa8fc
42ea40ed-8b12-4da3-aea6-ca7192d35290
13db1568-addf-4c60-be00-7c538c366245
b889c159-cf21-4193-99df-f2fe0275bce9
cd3bcf63-cf4b-4729-a1fb-bde413f9273d
99692a23-42a1-40d3-a41f-d5fb77bff691
008f496a-4c74-4cd4-9675-3f6a6e3a393c

why default argument in model always produce same uuid?

thanks


Solution

  • You're specifying a value for default instead of a function. Changing it to simply be default=uuid.uuid4 would result in the uuid4 function being called every time, giving you different values.