如何使用SQLAlchemy插入多对多关系数据?

时间:2018-11-06 17:26:15

标签: python sqlalchemy insert many-to-many

我要弄清楚的是一个有关如何将数据插入多对多关系的简单示例。我正在努力使用户可以成为许多团队的一部分,而一个团队也将拥有许多用户。

我阅读了SQLAlchemy文档,但没有显示如何实际将数据插入多对多关系。当我审视类似问题时,他们不会过多地插入多个元素-这正是我所需要的。它们主要显示如何通过关联表创建一个或进行更改。

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'))
    )

插入多对多数据

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=?
) ])

1 个答案:

答案 0 :(得分:0)

以下是使用SQLAlchemy ORM在多对多关联表中插入记录的一些示例,可能会对您有所帮助(分步显示,希望可以使其更轻松地跟踪每个记录中发生的事情不同的场景)。

如果您试图在关联表中创建将用户“ sam”和“ ashley”与“ wildcats”团队相关联的记录,则可以执行以下操作(假设您已经创建了User条记录“ sam”和“ ashley”,以及Teams记录“ wildcats”):

members = session.query(User).filter(User.name.in_(['sam', 'ashley'])).all()
wildcats = session.query(Teams).filter(Teams.name == 'wildcats').first()
wildcats.members = [member for member in members]
session.commit()

或者,如果您尝试使用关联用户“ sam”和“ ashley”创建新的“野猫” Teams记录,则可以修改以上内容以首先创建Teams记录。例如:

wildcats = Teams()
wildcats.name = 'wildcats'
members = session.query(User).filter(User.name.in_(['sam', 'ashley'])).all()
wildcats.members = [member for member in members]
session.add(wildcats)
session.commit()

或者,如果您尝试创建多个新的User记录并将它们与多个Teams记录相关联,则可以执行以下操作:

sam = User()
sam.name = 'sam'
sam_teams = session.query(Teams).filter(Teams.name.in_(['wildcats', 'jokers'])).all()
sam.teams = [team for team in sam_teams]
ashley = User()
ashley.name = 'ashley'
ashley_teams = session.query(Teams).filter(Teams.name.in_(['wildcats', 'horseman'])).all()
ashley.teams = [team for team in ashley_teams]
session.add_all([sam, ashley])
session.commit()