所以我試圖在這兩個表格之間實現一個簡單的一對多關係。我已經閱讀了文檔,刮網,投入了大量的工作來解決這個問題,所以我轉向你。使用一對多關係創建不使用主鍵的表格
我可以完全訪問數據庫,並且能夠創建其他表格,並具有可以工作的類似關係。
我正在使用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:[email protected]/database?host=localhost?port=3306")
base.metadata.create_all(engine)
if __name__ == '__main__':
main()
這是行不通的。
和失敗:
sqlalchemy.exc.InternalError:(pymysql.err.InternalError)(1005, '可以\' 噸創建表Trading
ticks
(錯誤: 「被錯誤地形成外鍵約束」 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)
以其他順序創建表。 –