SQLAlchemy

时间:2017-09-11 16:32:04

标签: python mysql sqlalchemy mysql-python

我正在尝试从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.

我环顾了一下,我确定它们都是同一类型(它们都是)并且都是主键(它们之前没有)但错误仍然存​​在。

有没有人能够深入了解造成这种情况的原因?

1 个答案:

答案 0 :(得分:2)

由于会议室有一个复合主键:(hotel_no,room_no),您需要在预订表上的外键关系中指定两列:

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