简体   繁体   中英

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:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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