如何使用SQLAlchemy创建多对多的关系?

时间:2015-02-23 07:30:27

标签: python sqlalchemy

如何使用以下模型创建多对多关系:

class Association(Base):
    a_id = Column(BigInteger, ForeignKey('a.id'), index=True)
    b_id = Column(String, ForeignKey('b.some_other_id'))

class A(Base):
     id = Column(BigInteger, primary_key=True)

class B(Base):
     id = Column(BigInteger, primary_key=True)
     some_other_id = Column(String(100), index=True, unique=True)

2 个答案:

答案 0 :(得分:1)

使用relationship的{​​{1}}功能,并确保在联接表中声明主键。

sqlalchemy.orm

答案 1 :(得分:1)

SQLAlchemy documentation进行调整:如果您不需要为关联添加额外的属性,则根本不需要关联模型:

association_table = Table('association', Base.metadata,
    Column('a_id', Integer, ForeignKey('a.id')),
    Column('b_id', Integer, ForeignKey('b.some_id'))
)

class A(Base):
    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)
    b_s = relationship("B",
                    secondary=association_table,
                    backref="a_s")

class B(Base):
    __tablename__ = 'b'
    some_id = Column(Integer, primary_key=True)

然后b.a_sA的集合,a.b_sB的集合;其中的更改将反映在session.flush()上的数据库中。

如果您执行希望为每个AB之间的关联添加额外的属性,那么您可以使用Association object pattern

class Association(Base):
    __tablename__ = 'association'
    left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
    right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
    extra_data = Column(String(50))
    child = relationship("Child")

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Association")

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)