Search code examples
djangodjango-modelscassandraprimary-keycql3

Python/Django: Create table with two primary_key using cql engine


I want create a table with two primary_key by it's django model as below:

class UserView(Model):
    email= columns.Text(primary_key=True)
    entryLink= columns.Text(primary_key=True)
    date= columns.Date(default=datetime.date.today())

but when I want create table as below:

>>> from cqlengine import connection
>>> from cqlengine.management import create_table
>>> from MainAPP.models import UserView
>>> connection.setup(['127.0.0.1:9160'])
>>> create_table(UserView)

I see this error:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "H:\Web-Programming\Python\Project\Prexter\Virtual-Environment\Lib\site-packages\cqlengine\management.py", line 97, in create_table
execute(qs)
  File "H:\Web-Programming\Python\Project\Prexter\Virtual-Environment\Lib\site-packages\cqlengine\connection.py", line 172, in execute
return connection_pool.execute(query, params)
  File "H:\Web-Programming\Python\Project\Prexter\Virtual-Environment\Lib\site-packages\cqlengine\connection.py", line 164, in execute
    raise CQLEngineException(unicode(ex))
CQLEngineException: Bad Request: Missing CLUSTERING ORDER for column entryLink

When I remove primary_key property from entryLink field, I have no error! but I want define entryLink as a primary_key! What is my mistake?


Solution

  • A database table cannot have 2 primary key. If you are looking for a Composite Primary Key, Django does not support that yet.

    Now, what you might be looking for is unique=True (a candidate key).

    class UserView(Model):
        email= columns.Text(primary_key=True)
        entryLink= columns.Text(unique=True)
        date= columns.Date(default=datetime.date.today())
    

    You can also read this post for a better understanding