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,应注意,否则在进行数据删除时将会报错。
30 book_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)