What I am trying to figure out is a simple example on how to insert data into a many-to-many relationship. I am trying to make it where a user can be a part of many teams, while also a team would have many users.
I read the SQLAlchemy documentation but they don't show how to actually insert data into a many to many relationship. When I review SO similar questions, they don't go over inserting multiple elements - which is what I need. They mainly show how to create one through an association table or make changes.
class Teams(Base):
__tablename__ = 'teams'
id = Column(Integer, primary_key=True)
name = Column(String(64))
members = relationship('User', secondary=teams_association, back_populates='teams')
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String(64))
teams = relationship('Teams', secondary=teams_association, back_populates='members')
teams_association = Table(
'teams_association',
Base.metadata,
Column('captain_id', Integer, ForeignKey('user.id')),
Column('teams_id', Integer, ForeignKey('teams.id'))
)
Inserting many-to-many data
session.add_all([
Teams(
name='wildcats',
members=?? # <-- Members [1,3,4] How would I do a multiple insert here?
),
Teams(
name='horseman',
members=??
),
Teams(
name='jokers',
members=??
) ])
session.commit()
session.add_all([
User(
name='sam',
teams=? # [1,3] ex. A Member of Teams 1(wildcats) & 3(jokers)
),
User(
name='ashley',
teams=?
),
User(
name='jackson',
teams=?
),
User(
name='ethan',,
teams=?
),
User(
name='miles',
teams=?
) ])