簡體   English   中英

SQLAlchemy的外鍵約束錯誤

[英]Error in foreign key constraint with SQLAlchemy

我現在正在嘗試從SQLAlchemy的一門老課程中實現非常簡單的示例表...

我已經走了這么遠,但是當我運行代碼時...

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_args__ = (
        ForeignKeyConstraint(
            ['hotel_no', 'room_no'],
            ['rooms.hotel_no', 'rooms.room_no']
        ),
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM