mercredi 23 mars 2016

SQLAlchemy composite primary key

I'm trying to create a composite primary key with SQLAlchemy however when adding data it's telling me that the columns are not unique but, as a pair, I'm sure that they are.

Is there something wrong with my syntax?

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
import dataset


Base = declarative_base()

class Work(Base):
    __tablename__ = 'Work'
    id = Column(String(25),primary_key=True)
    user = Column(String(10),primary_key=False)
    date = Column(Integer, primary_key=False)
    time = Column(Integer, primary_key=False)
    ticket = Column(String(10), primary_key=True)
    updated = Column(Integer, primary_key=False)
    timestamp = Column(Integer, primary_key=False)

engine = create_engine('sqlite:///work_items.db', pool_recycle=3600)
Base.metadata.create_all(engine)

I've defined the id and ticket columns as primary keys True, which is how I'm supposed to do it according to the docs - I just can't seem to figure out what's causing this issue.

I know that I could simply define the id column as a string composed of a concatenation of id+ticket, but I thought it would be better to the composite primary key feature because that's what the feature's for!

EDIT: It has been suggested that another question regarding defining a foreign key constraint on a composite primary key serves as an answer to this question. However, it does not: my database has only one table, and therefore no foreign key relationships. Despite that, I am still encountering an error:

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) columns id, ticket are not unique

Aucun commentaire:

Enregistrer un commentaire