Reputation: 1879
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?
Upvotes: 0
Views: 252
Reputation: 360
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.
Upvotes: 1