[英]Error when creating many to many relationship in sqlalchemy
我正在使用sqlalchemy文檔中的以下代碼( http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many )創建多對多表關系:
association_table = Table('association', Base.metadata,
Column('left_id', Integer, ForeignKey('left.id')),
Column('right_id', Integer, ForeignKey('right.id'))
)
class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True)
children = relationship(
"Child",
secondary=association_table,
back_populates="parents")
class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
parents = relationship(
"Parent",
secondary=association_table,
back_populates="children")
運行應用程序時,出現以下錯誤:
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) relation "left" does not exist
[SQL: '\nCREATE TABLE association_table (\n\tleft_id INTEGER, \n\tright_id INTEGER, \n\tFOREIGN KEY(left_id) REFERENCES left (id), \n\tFOREIGN KEY(right_id) REFERENCES right (id)\n)\n\n']
似乎是雞和雞蛋的問題-我似乎無法創建association_table,因為不存在Parent(即“左”)-但我不能先創建它,因為它稱為association_table。
有任何想法嗎?
嘗試在關系中使用表的字符串名稱。
class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True)
children = relationship(
"Child",
secondary='association',
back_populates="parents")
class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
parents = relationship(
"Parent",
secondary='association',
back_populates="children")
association_table = Table('association', Base.metadata,
Column('left_id', Integer, ForeignKey('left.id')),
Column('right_id', Integer, ForeignKey('right.id'))
)
這樣,輔助聯接中的關聯表是從基本元數據表中獲取的,而不是順序執行查詢,我想這可能是錯誤的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.