0

I have two classes:

"Test1":

class Test1(Base):
 data = [
 [1, 2],
 [3, 4],
 ]
 a = Column(Integer, primary_key=True)
 b = Column(Integer, primary_key=True)
 def __init__(self, a, b):
 self.a = a
 self.b = b

that will be referenced by "Test2":

class Test2(Base):
 data = [
 [1, 1, 2],
 [2, 3, 4],
 ]
 id = Column(Integer, primary_key=True)
 c = Column(ForeignKey(Test1.a))
 d = Column(ForeignKey(Test1.b))
 __table_args__ = (ForeignKeyConstraint([c, d], [Test1.a, Test1.b]), {})
 def __init__(self, id, c, d):
 self.id = id
 self.c = c
 self.d = d

When trying to make these in SQLAlchemy (Python 3) using a local PostgreSQL database, I get this error:

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) there is 
no unique constraint matching given keys for referenced table "Test1"
[SQL: '\nCREATE TABLE "Test2" (\n\tid SERIAL NOT NULL, \n\ta1 INTEGER, 
\n\tb1 INTEGER, \n\tPRIMARY KEY (id), \n\tFOREIGN KEY(a1, b1) 
REFERENCES "Test1" (a, b), \n\tFOREIGN KEY(a1) REFERENCES "Test1" (a), 
\n\tFOREIGN KEY(b1) REFERENCES "Test1" (b)\n)\n\n'] (Background on this 
error at: http://sqlalche.me/e/f405)

Just to summarize, I am trying to make a table that references another table via the referenced table's composite foreign key, but with about 10 attempts for a workaround, I am unable to resolve this. Golden cookie to whomever does.

Ilja Everilä
53.3k9 gold badges137 silver badges141 bronze badges
asked May 8, 2018 at 18:40
0

1 Answer 1

1

Neither Test1.a nor Test1.b is a (unique) key on its own, though you try to reference them as such with ForeignKey(Test1.a) and ForeignKey(Test1.b). Just remove those. The composite foreign key you've defined as well is correct.

answered May 8, 2018 at 19:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.