0

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.

Atte Juvonen
  • 4,922
  • 7
  • 46
  • 89
  • You can find an answer to your main question [here](https://stackoverflow.com/questions/7417906). As for why declaring `bridge` as a mapped class `Bridge` doesn't work, you need to replace `bridge` in your class definitions with with `Bridge.__table__`. (Of course you'd otherwise get "unresolved reference", because you haven't defined `bridge` anywhere!) – univerio Jul 21 '17 at 21:27
  • I adapted the example you linked. Now I don't get errors from adding links, but they don't end up in the database. Again, I can add to the regular tables, but not to the bridge table. I don't know how to debug this when it's not giving errors. – Atte Juvonen Jul 21 '17 at 21:54
  • You'll have to post a [mcve]. It's not possible to debug if you only provide the symptoms and not what you're doing. – univerio Jul 21 '17 at 22:00
  • Posted MCVE now. – Atte Juvonen Jul 22 '17 at 17:58
  • You have extra commas at the end of some of your lines. – univerio Jul 22 '17 at 17:59
  • Great, I now have a working MCVE based on the example you linked. Thanks again! – Atte Juvonen Jul 22 '17 at 18:03

0 Answers0