sqlalchemy.exc.ProgrammingError :( ProgrammingError)没有唯一约束匹配给定引用表的键

时间:2014-01-26 11:21:18

标签: postgresql indexing sqlalchemy foreign-keys

我使用sqlalchemy在下面创建两个表:

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'))

但是,我得到了错误说:

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

1 个答案:

答案 0 :(得分:14)

我刚想通了,在这种情况下我需要有一个多列外键约束: 将我的部分模型更改为:

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]), {})

一切正常。