pythoncassandracqlenginedatastax-python-driver

How to dynamically define CQLEngine models?


I am using Datastax's Cassandra Python driver's Object Mapper for defining cassandra table columns. I am trying to define the models at run time (that's the requirement). The table and column names and column types are resolved at run time.

I am trying to define a cassandra cqlengine model at runtime using type to define a class.

Looks like the Model class defined on the Python driver has added a metaclass to Model:

@six.add_metaclass(ModelMetaClass)
class Model(BaseModel):
...

Is there even a way to define Models using type?

I am seeing the following error while defining a Model class:

from cassandra.cqlengine.models import Model
from cassandra.cqlengine import columns as Columns

attributes_dict = {
    'test_id': Columns.Text(primary_key=True)
    'test_col1': Columns.Text()
}

RunTimeModel = type ('NewModelName', tuple(Model), attributes_dict)

Error:

RunTimeModel = type ('NewModelName', tuple(Model), attributes_dict)
TypeError: 'ModelMetaClass' object is not iterable

Solution

  • I think you have a simple syntax error trying to construct a tuple from a non-sequence argument.

    Instead, you can use the tuple literal notation:

    RunTimeModel = type ('NewModelName', (Model,), attributes_dict)