首页 > 数据库技术 > 详细

Python SQLAlchemy多对多外键关联时表结构

时间:2019-02-19 20:25:06      阅读:252      评论:0      收藏:0      [点我收藏+]
 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)

 

Python SQLAlchemy多对多外键关联时表结构

原文:https://www.cnblogs.com/zepc007/p/10403112.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!