因此,我试图在这两个表之间实现简单的一对多关系。我已经阅读了文档,刮了一下网,做了很多工作来解决这个问题,所以我请您解决。
我拥有对数据库的完全访问权限,并且能够创建其他具有相似关系的表。
我正在使用mariadb,“ mysql”。
表Tradable中的每一行都有一个tick_size_id,而每一行都有一个tick_size_id。我想将它们与该专栏联系起来,我似乎无法弄清楚该如何做。
base = declarative_base()
class Tradables(base):
__tablename__ = "tradables"
id = Column(Integer, primary_key=True)
tick_size_id = Column(Integer, nullable=False)
ticks = relationship("Ticks")
class Ticks(base):
__tablename__ = "ticks"
id = Column(Integer, primary_key=True)
tick_size_id = Column(Integer, ForeignKey("tradables.tick_size_id"))
def main():
engine = create_engine("mysql+pymysql://user:password@localhost/database?host=localhost?port=3306")
base.metadata.create_all(engine)
if __name__ == '__main__':
main()
这是行不通的。
并失败:
sqlalchemy.exc.InternalError:(pymysql.err.InternalError)(1005,'无法创建表Trading
。ticks
(errno:150“外键约束格式不正确”))')[SQL:'\ n
CREATE TABLE ticks (\n\t
id INTEGER NOT NULL AUTO_INCREMENT, \n\t
tick_size_id INTEGER, \n\t
PRIMARY KEY (id), \n\t
FOREIGN KEY(tick_size_id) REFERENCES tradables (tick_size_id)\n)\n\n']
我究竟做错了什么?
编辑:
尝试了这两个创建顺序,并且都给出了相同的结果。
base.metadata.tables["ticks"].create(bind=engine)
base.metadata.tables["tradables"].create(bind=engine)
和
base.metadata.tables["tradables"].create(bind=engine)
base.metadata.tables["ticks"].create(bind=engine)
您需要在上有一个索引tradables.tick_size_id
。我不是炼金术士,但我想那就像
...
__tablename__ = "tradables"
id = Column(Integer, primary_key=True)
tick_size_id = Column(Integer, nullable=False, index=True)
ticks = relationship("Ticks")
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句