hashchen
hashchen

Reputation: 1041

sqlalchemy.exc.ProgrammingError: (ProgrammingError) there is no unique constraint matching given keys for referenced table

I am using sqlalchemy to create two tables in the following:

class Classroom(Base):
    __tablename__ = 'classroom'
    building = Column(String(256), primary_key = True)
    room_no = Column(String(256), primary_key = True)
    capacity = Column(Integer)

class Section(Base):
    __tablename__ = 'section'
    course_id = Column(String(256), ForeignKey('course.course_id'), primary_key = True)
    building = Column(String(256), ForeignKey('classroom.building'))
    room_no = Column(String(256), ForeignKey('classroom.room_no'))

However, I got the error saying:

 sqlalchemy.exc.ProgrammingError: (ProgrammingError) there is no unique constraint matching given keys for referenced table "classroom"

Upvotes: 8

Views: 3015

Answers (1)

hashchen
hashchen

Reputation: 1041

I just figured out, in this case I need to have a multicolumn foreig key constraints: Changed my section model to be:

class Section(Base):
    __tablename__ = 'section'
    course_id = Column(String(256), ForeignKey('course.course_id'), primary_key = True)
    building = Column(String(256))
    room_no = Column(String(256))
    __table_args__ = (ForeignKeyConstraint([building, room_no],[Classroom.building, Classroom.room_no]), {})

and everything works.

Upvotes: 16

Related Questions