Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 274
user2002692 Avatar asked Jan 26 '14 11:01

user2002692


People also ask

How do I add a unique constraint to an existing table?

The syntax for creating a unique constraint using an ALTER TABLE statement in SQL Server is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.

Can I use unique key as foreign key?

A foreign key can refer to either a unique or a primary key of the parent table. If the foreign key refers to a non-primary unique key, you must specify the column names of the key explicitly.

How do I add a primary key constraint to an existing table in PostgreSQL?

In PostgreSQL, a primary key is created using either a CREATE TABLE statement or an ALTER TABLE statement. You use the ALTER TABLE statement in PostgreSQL to add or drop a primary key.


1 Answers

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.

like image 98
user2002692 Avatar answered Sep 17 '22 08:09

user2002692