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

时间:2017-10-23 14:17:49

标签: python postgresql 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']

这似乎是一个鸡和蛋的问题 - 我似乎无法创建assoc_table作为Parent(即' left')不存在 - 但我不能创建它,因为它调用association_table。 / p>

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

尝试使用关系中表格的字符串名称。

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

这样,辅助连接中的关联表是从Base元数据表中获取的,而不是按顺序执行查询,我猜这将是错误的原因。