我的项目是一个基于Python、MySql和SQLAlchemy的项目。但是当我尝试执行该项目时,它给了我这个问题:
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (3780, "Referencing column 'city_id' and referenced column 'id' in foreign key constraint 'places_ibfk_1' are incompatible."
片段:
[SQL:
CREATE TABLE places (
id VARCHAR(60) NOT NULL,
created_at DATETIME,
updated_at DATETIME,
city_id VARCHAR(60) NOT NULL,
user_id VARCHAR(60) NOT NULL,
name VARCHAR(128) NOT NULL,
description VARCHAR(1024),
number_rooms INTEGER NOT NULL,
number_bathrooms INTEGER NOT NULL,
max_guest INTEGER NOT NULL,
price_by_night INTEGER NOT NULL,
latitude FLOAT,
longitude FLOAT,
PRIMARY KEY (id),
FOREIGN KEY(city_id) REFERENCES cities (id),
FOREIGN KEY(user_id) REFERENCES users (id)
)
]
(此错误的背景:https://sqlalche.me/e/14/e3q8)
无法理解问题的概念。正如错误消息所示,我尝试检查类型不兼容,但找不到。
这是城市的定义: 我已经在 city.py 文件中定义了城市模型。
class City(BaseModel, Base):
"""Representation of city """
if models.storage_t == "db":
__tablename__ = 'cities'
state_id = Column(String(60), ForeignKey('states.id'), nullable=False)
name = Column(String(128), nullable=False)
places = relationship("Place", backref="cities")
else:
state_id = ""
name = ""
如果您是 ALX 学生,则您使用的转储文件包含附加到正在创建的表的以下信息:
ENGINE=InnoDB DEFAULT CHARSET=latin1;
,其中 charset
设置为 latin1
,而 SQLAlchemy 或创建其表时的默认值,将此附加到其表中ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
,您可以看到,这将导致您所看到的冲突或错误sqlalchemy.exc.OperationalError: (MySQLdb.OperationalError) (3780, "Referencing column 'city_id' and referenced column 'id' in foreign key constraint 'places_ibfk_1' are incompatible.")
,因为在引用时,两个表在列长度、类型等方面应该相同且兼容在这种情况下,两个表的字符集不同,在这种情况下引用列是有点不可能的。
因此,消除转储文件中的 ENGINE=InnoDB DEFAULT CHARSET=latin1
将创建表并引用它们,不会出现任何问题。