简体   繁体   English

在sqlalchemy中创建多对多关系时出错

[英]Error when creating many to many relationship in sqlalchemy

I am using the following code from the sqlalchemy documentation ( http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many ) to create a many to many table relationship: 我正在使用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")

When I run the application I get the following error: 运行应用程序时,出现以下错误:

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']

It seems like a chicken and egg problem - I cant seem to create association_table as Parent (ie 'left') doesn't exist - but I cant create that first as it calls association_table. 似乎是鸡和鸡蛋的问题-我似乎无法创建association_table,因为不存在Parent(即“左”)-但我不能先创建它,因为它称为association_table。

Any ideas? 有任何想法吗?

Try using the string name of the table in the relationship. 尝试在关系中使用表的字符串名称。

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'))
)

This way the association table in the secondary join is taken from the Base metadata tables rather than executing the queries sequentially, which I guess would be the reason for the error. 这样,辅助联接中的关联表是从基本元数据表中获取的,而不是顺序执行查询,我想这可能是错误的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM