【问题标题】:Creating tables with a one to many relationship not using primary key不使用主键创建具有一对多关系的表
【发布时间】:2016-11-21 23:28:07
【问题描述】:

所以我试图在这两个表之间实现一个简单的一对多关系。我已经阅读了文档,上网,投入了大量工作来解决这个问题,所以我求助于你。

我拥有对数据库的完全访问权限,并且能够创建具有类似关系的其他表。

我正在使用 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, 'Can\'t create table 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)

【问题讨论】:

  • 按其他顺序创建表。

标签: python sqlalchemy mariadb


【解决方案1】:

您需要在tradables.tick_size_id 上有一个索引。我不是炼金术士,但我想应该是这样的

...
__tablename__ = "tradables"

id = Column(Integer, primary_key=True)
tick_size_id = Column(Integer, nullable=False, index=True)
ticks = relationship("Ticks")
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多