In SQLAlchemy I've declared 2 classes with a composite primary key and would like a many-to-many relation between them. This:
class Topic(Base):
__tablename__ = 'topic'
id = Column(BigInteger, primary_key=True)
repo = Column(String, primary_key=True)
class Label(Base):
__tablename__ = 'label'
repo = Column(String, primary_key=True)
title = Column(String(25), primary_key=True)
class TopicLabel(Base):
__tablename__ = 'topic_label'
topic_id = Column(BigInteger, primary_key=True)
topic_repo = Column(String, primary_key=True)
label_repo = Column(String, primary_key=True)
label_title = Column(String, primary_key=True)
__table_args__ = (
ForeignKeyConstraint(
['topic_id', 'topic_repo'],
['topic.id', 'topic.repo'],
),
ForeignKeyConstraint(
['label_repo', 'label_title'],
['label.repo', 'label.title'],
),
)
This results in the following error:
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidForeignKey) there is no unique constraint matching given keys for referenced table "label"
[SQL:
CREATE TABLE topic_label (
topic_id BIGINT NOT NULL,
topic_repo VARCHAR NOT NULL,
label_repo VARCHAR NOT NULL,
label_title VARCHAR NOT NULL,
PRIMARY KEY (topic_id, topic_repo, label_repo, label_title),
FOREIGN KEY(label_repo, label_title) REFERENCES label (repo, title),
FOREIGN KEY(topic_id, topic_repo) REFERENCES topic (id, repo)
)
]
What am I doing wrong here?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…