How to build many-to-many relations using SQLAlchemy: a good example

后端 未结 1 987
半阙折子戏
半阙折子戏 2020-12-08 16:24

I have read the SQLAlchemy documentation and tutorial about building many-to-many relation but I could not figure out how to do it properly when the association table contai

相关标签:
1条回答
  • 2020-12-08 16:43

    From the comments I see you've found the answer. But the SQLAlchemy documentation is quite overwhelming for a 'new user' and I was struggling with the same question. So for future reference:

    ItemDetail = Table('ItemDetail',
        Column('id', Integer, primary_key=True),
        Column('itemId', Integer, ForeignKey('Item.id')),
        Column('detailId', Integer, ForeignKey('Detail.id')),
        Column('endDate', Date))
    
    class Item(Base):
        __tablename__ = 'Item'
        id = Column(Integer, primary_key=True)
        name = Column(String(255))
        description = Column(Text)
        details = relationship('Detail', secondary=ItemDetail, backref='Item')
    
    class Detail(Base):
        __tablename__ = 'Detail'
        id = Column(Integer, primary_key=True)
        name = Column(String)
        value = Column(String)
        items = relationship('Item', secondary=ItemDetail, backref='Detail')
    
    0 讨论(0)
提交回复
热议问题