SQLAlchemy 的外键约束错误

Error in foreign key constraint with SQLAlchemy

我正在尝试在 SQLAlchemy 中实现一个旧课程中的非常简单的示例 table...

我已经走到这一步了,但是当我 运行 代码时...

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Date, MetaData
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()
engine = create_engine('mysql://x @ amazonaws.com:3306/db', echo=True)
class Guest(Base):
    __tablename__ = "guests"
    guest_no = Column(String(4), primary_key=True)
    g_name = Column(String(20))
    g_address = Column(String(30))
    booking = relationship("Booking", back_populates="guests")
class Hotel(Base):
    __tablename__ = "hotels"
    hotel_no = Column(String(4), primary_key=True)
    h_name = Column(String(20))
    h_address = Column(String(30))
    room = relationship("Room", back_populates="hotels")
    booking = relationship("Booking", back_populates="hotels")
class Room(Base):
    __tablename__ = "rooms"
    hotel_no = Column(String(4), ForeignKey('hotels.hotel_no'), primary_key=True)
    room_no = Column(String(4), primary_key=True)
    r_type = Column(String(1))
    r_price = Column(Integer)
    hotel = relationship("Hotel", back_populates="rooms")
    booking = relationship("Booking", back_populates="rooms")
class Booking(Base):
    __tablename__ = "bookings"
    hotel_no = Column(String(4), ForeignKey('hotels.hotel_no'),  primary_key=True)
    guest_no = Column(String(4), ForeignKey('guests.guest_no'), primary_key=True)
    date_form = Column(Date, primary_key=True)
    date_to = Column(Date)
    room_no = Column(String(4), ForeignKey('rooms.room_no'), primary_key=True)
    hotel = relationship("Hotel", back_populates="bookings")
    guest = relationship("Guest", back_populates="bookings")
    room = relationship("Room", back_populates="bookings")

Base.metadata.create_all(engine)

它给我一个关于 room_no 外键的错误...

2017-09-11 16:16:03 2b8010c29700 Error in foreign key constraint of table db/bookings:
FOREIGN KEY(room_no) REFERENCES rooms (room_no)
):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.

我环顾四周,确保它们都是同一类型(它们是)并且都是主键(它们以前不是)但错误仍然存​​在。

有谁知道造成这种情况的原因吗?

因为房间有复合主键:(hotel_no,room_no)您需要在预订时指定外键关系中的两列table:

__table_args__ = (
        ForeignKeyConstraint(
            ['hotel_no', 'room_no'],
            ['rooms.hotel_no', 'rooms.room_no']
        ),
)