1、先把需要做多對多的模型定義出來
2、使用Table定義一個中間表,中間表一般就是包含兩個模型的外鍵字段就可以了,並且讓他們兩個來作為一個“復合主鍵”
3、在兩個需要做多對多的模型中隨便選擇一個模型,定義一個relationship屬性,來綁定三者之間的關系,在使用relationship的時候需要傳入一個secondary中間表
1 #encoding:utf8 2 # sqlalchemy創建多對多的關系表 3 from sqlalchemy import create_engine,Column,Integer,String,Table,ForeignKey 4 from sqlalchemy.ext.declarative import declarative_base 5 from mysql_config import DB_URI 6 from sqlalchemy.orm import sessionmaker,relationship 7 8 9 # 數據庫連接代碼從from mysql_config import DB_URI中導入 10 # mysql連接格式 11 # DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/{database}".format("這里填寫需要的數據") 12 13 engine = create_engine(DB_URI) 14 Base = declarative_base(engine) 15 session = sessionmaker(engine)() 16 17 article_tag = Table( 18 "article_tag", 19 Base.metadata, 20 Column("article_id",Integer,ForeignKey("article.id"),primary_key=True), 21 Column("tag_id",Integer,ForeignKey("tag.id"),primary_key=True) 22 ) 23 class Article(Base): 24 __tablename__ = "article" 25 id = Column(Integer,primary_key=True,autoincrement=True) 26 title = Column(String(50),nullable=False) 27 tags = relationship("Tag",backref="articles",secondary=article_tag) 28 def __repr__(self): 29 return "<Article(title:%s)>"%self.title 30 class Tag(Base): 31 __tablename__ = "tag" 32 id = Column(Integer, primary_key=True, autoincrement=True) 33 name = Column(String(50), nullable=False) 34 def __repr__(self): 35 return "<Article(name:%s)>"%self.name 36 37 def create_table(): 38 Base.metadata.create_all() 39 40 #測試數據,分別給article1、article2、tag1、tag2添加兩條數據 41 def add_data(): 42 article1 = Article(title="article1") 43 article2 = Article(title="article2") 44 tag1 = Tag(name="tag1") 45 tag2 = Tag(name="tag2") 46 47 tag1.articles.append(article1) 48 tag1.articles.append(article2) 49 50 tag2.articles.append(article1) 51 tag2.articles.append(article2) 52 session.add(tag1) 53 session.add(tag2) 54 session.commit() 55 56 # 這是數據庫插入后的數據 57 # mysql> select * from article 58 # -> ; 59 # +----+----------+ 60 # | id | title | 61 # +----+----------+ 62 # | 1 | article1 | 63 # | 2 | article2 | 64 # +----+----------+ 65 # 2 rows in set (0.00 sec) 66 # 67 # mysql> select * from tag 68 # -> ; 69 # +----+------+ 70 # | id | name | 71 # +----+------+ 72 # | 1 | tag1 | 73 # | 2 | tag2 | 74 # +----+------+ 75 # 2 rows in set (0.00 sec) 76 # 77 # mysql> select * from article_tag 78 # -> ; 79 # +------------+--------+ 80 # | article_id | tag_id | 81 # +------------+--------+ 82 # | 1 | 1 | 83 # | 2 | 1 | 84 # | 1 | 2 | 85 # | 2 | 2 | 86 # +------------+--------+ 87 # 4 rows in set (0.00 sec) 88 89 #測試查詢 90 def search_data(): 91 article = session.query(Article).first() 92 print("這是通過article參數查找tags:%s"%article.tags) 93 tag = session.query(Tag).first() 94 print("這是通過tag參數查找article:%s"%tag.articles) 95 96 if __name__ == "__main__": 97 # create_table 98 # add_data() 99 search_data()