Python SQLAlchemy多對多外鍵關聯時表結構
阿新 • • 發佈:2019-02-19
reat 表結構 clas python asc int port pre 創建
1 # 創建多對多表結構 2 from sqlalchemy.ext.declarative import declarative_base 3 from sqlalchemy.engine import create_engine 4 from sqlalchemy import INTEGER, Column, CHAR, ForeignKey 5 from sqlalchemy.orm import relationship 6 Base = declarative_base() 7 class Book(Base): 8 __tablename__= ‘book‘ 9 id = Column(INTEGER, primary_key=True) 10 name = Column(CHAR(20), nullable=False) 11 b2t = relationship(‘Tag‘, backref=‘t2b‘, secondary=‘booktag‘) 12 13 def __str__(self): 14 return self.name 15 16 17 class Tag(Base): 18 __tablename__ = ‘tag‘ 19 id = Column(INTEGER, primary_key=True)20 name = Column(CHAR(20), nullable=False) 21 22 def __str__(self): 23 return self.name 24 25 26 class BookTag(Base): 27 __tablename__ = ‘booktag‘ 28 id = Column(INTEGER, primary_key=True) 29 # ondelete、onupdate設置為同步更新、同步刪除,代碼中對應的值為CASCADE,應註意,否則在進行數據刪除時將會報錯。 30book_id = Column(INTEGER, ForeignKey(‘book.id‘, ondelete=‘CASCADE‘, onupdate=‘CASCADE‘)) 31 tag = Column(INTEGER, ForeignKey(‘tag.id‘, ondelete=‘CASCADE‘, onupdate=‘CASCADE‘)) 32 33 34 engine = create_engine("mysql+mysqlconnector://root:@127.0.0.1:3306/sqlalchemy?charset=utf8") 35 if __name__ == ‘__main__‘: 36 Base.metadata.create_all(engine)
Python SQLAlchemy多對多外鍵關聯時表結構