我想在数据库中关联两个表。我为此项目使用sqlalchemy和mariadb。
当表描述中的列描述设置为String且最大值为700时,效果很好。
class Edition(Base):
__tablename__= "edition"
idEdition = Column(Integer, primary_key=True)
description = relationship("Description", back_populates="edition")
class Description(Base):
__tablename__ = "description"
idDescription = Column(Integer, primary_key=True)
edition_id = Column(Integer, ForeignKey('edition.idEdition'), nullable=False)
description = Column(String(700), nullable=False)
edition = relationship("Edition", back_populates="description")
UniqueConstraint(edition_id, description)
但是我需要存储更长的描述。如果我尝试description = Column(String(800), nullable=False)
有错误:
sqlalchemy.exc.DatabaseError: (mysql.connector.errors.DatabaseError) 1005 (HY000): Can't create table `bestsellers`.`description` (errno: 150 "Foreign key constraint is incorrectly formed")
与description = Column(LONGTEXT, nullable=False)
我认为类型有问题,但目前无法找到...
编辑 根据Gord Thompson的建议,我更改了Description类:
class Description(Base):
__tablename__ = "description"
idDescription = Column(Integer, primary_key=True)
edition_id = Column(Integer, ForeignKey('edition.idEdition'), nullable=False)
description = Column(LONGTEXT, nullable=False)
description_short = Column(String(750), nullable=False)
edition = relationship("Edition", back_populates="description")
UniqueConstraint(edition_id, description_short)
,它似乎正在工作。但是,我不知道mysql:
CREATE TABLE description (idDescription INTEGER NOT NULL AUTO_INCREMENT,
edition_id INTEGER NOT NULL, description LONGTEXT NOT NULL, PRIMARY KEY
(`idDescription`), UNIQUE (edition_id, description(750)), FOREIGN KEY(edition_id)
REFERENCES edition (`idEdition`));
可以直接翻译成python sqlalchemy吗?我宁愿不添加新列。出于UniqueConstraint
的目的,仅限制现有列会很好。