Search code examples
pythoncassandracqlengine

Cassandra. Default column value


Following example from python cassandra driver

class Users(Model):
    username = columns.Text(index=True, required=True)
    user_id = columns.UUID(index=True, default=uuid.uuid4)
    email = columns.Text(primary_key=True, required=True)
    passwd = columns.Text()
    salt = columns.Text()

And creating object in following way:

u = Users()
u.username = 'admin'
u.email = '[email protected]'
u.password = u'test'   #This is property with setter
Users.create(**dict(u))

In this case, we get user_id:None instead of user_id:uuid.uuid4 and corresponding error.

How to make default = uuid.uuid4 work with less pain?

UPD I guess, it's caused by overriding to_database method in UUID column. Which conflicts with base to_database method.

UPD2 Looks like bad case. Error happens on step **dict(u)

Solution:

d = dict(u) 
del d['column_with_default_value']
Users.create(**d)

Solution

  • You're doing a lot more work than you need to. Given your table, this is how you insert:

    Users.create(username="admin", email="[email protected]", passwd="test")

    I've verified this here:

    In [16]: Users.create(username="admin", email="[email protected]", passwd="test") Out[16]: Users(username='admin', user_id=UUID('183d542d-c469-448d-9d14-d3614f727cef'), email='[email protected]', passwd='test', salt=None)