【问题标题】:SQLAlchemy - Traditional and Declarative mapping in many-to-manySQLAlchemy - 多对多中的传统和声明式映射
【发布时间】:2016-05-18 22:26:29
【问题描述】:

根据 SQLAlchemy 的多对多关系文档,连接表是使用传统映射声明的。其他表是使用声明式映射声明的。

为什么不只使用一种类型的映射,比如声明式?在这种情况下可能吗?

    association_table = Table('association', Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id'))
)

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

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

【问题讨论】:

    标签: sqlalchemy


    【解决方案1】:

    这绝对有可能,但人们通常不这样做的原因仅仅是因为他们通常不想像使用对象一样使用关联表。

    它看起来像:

    class Left(Base):
        __tablename__ = 'left'
        id = Column(Integer, primary_key=True
    
    class Right(Base):
        __tablename__ = 'right'
        id = Column(Integer, primary_key=True)
    
    class M2MRightLeft(Base):
        __tablename__ = 'm2m_right_left'
        left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
        right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
    

    话虽如此,我通常会坚持使用传统的 M2M 关系映射。一般情况下,如果我想在 M2M 表中添加额外的列,我只会使用声明式样式。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 2011-12-05
    • 2011-06-19
    • 2017-11-25
    • 1970-01-01
    相关资源
    最近更新 更多