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"
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With