My question is how to insert rows to a bridge table with SQLAlchemy? I tried to look up similar examples, but they can't be directly applied here for 2 reasons: the bridge table has an additional column, and also, the referenced objects already exist and we don't want to recreate them.
Let's say I have 3 tables: socks, shoes and bridge. Bridge table has 3 columns:
- ForeignKey_socks
- ForeignKey_shoes
- Integer.
I've defined the database schema similarly as they do in tutorials (see Many To Many -section), where "normal" tables are defined as classes and bridge table as a Table:
bridge = Table(...)
class Sock(Base): ...
class Shoe(Base): ...
I checked with psql that the database schema appears to be created correctly. I can insert Socks and Shoes. Errors come when I try to insert something into the bridge table.
First, I tried to insert rows like I would to any normal table:
link = bridge(...)
db.add(link)
db.commit()
The commit line yields TypeError: Table object is not callable
. I assume this is because bridge is defined without the class declaration. I found another example where they do declare a class for the bridge table as well, so I tried that. If I declare a class instead of a "Table", my other classes break because of Unresolved reference 'bridge'
. Doesn't matter which order the classes are declared. If I declare both a Table and a class, I get an already defined
error. I also tried guessing various other syntax options, but I'm running out of ideas at this point.