postgresql - sqlalchemy.exc.编程错误 : (ProgrammingError) there is no unique constraint matching given keys for referenced table

标签 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"

最佳答案

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

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

一切正常。

关于postgresql - sqlalchemy.exc.编程错误 : (ProgrammingError) there is no unique constraint matching given keys for referenced table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21362732/

相关文章:

r - R 中的逻辑索引失败

MongoDB:按键迭代集合?

python - 与 sqlite3 数据库上的表单提交中的 sqlalchemy 行更新行为不一致

python - SQLAlchemy 引擎和 session 对象的类型提示

sql - 合并两个 Postgresql 查询

postgresql - AlloyDB 读取池数据似乎已过时

mysql - 找到多列索引的最佳顺序

postgresql - Docker-Compose 和 Postgres 扩展

postgresql - 如何在 postgres 扩展的 Makefile 中为 installcheck 设置用户?

python - 如何使用 sqlalchemy 对整数支持的枚举进行建模?