[英]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.