SQLAlchemy之ManyToMany

接上一篇:https://www.jianshu.com/p/161205d5c4b7

乔巴.png

一对多和多对多最大的区别在于第三张表上,也就是说这两张表没有直接关系,需要第三张关系表来连接两张表,且SQLAlchemy虽然可以自动生成第三张表,但是它并不友好。因此不讨论,这里我们手动创建第三张表。

1 建立关系
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

from sqlalchemy import Column, Integer, String, Foreignkey
from sqlalchemy.orm import relationship


class Girls(Base):
   __tablename__ = "girl"
    id = Column(Integer,primary_key=True)
   name = Column(String(32))
    g2b = relationship("Boys",backref="b2g",secondary="hotel")  # secondary作为中间桥梁(媒婆),关联上Boys对象,也就是这一篇幅的核心多对多关系就这样产生了


class Boys(Base):
   __tablename__ = "boy"
    name = Column(String(32))
    
    
class Hotel(Base):
   __tablename__ = "hotel"
    id = Column(Integer,primary_key=True)
   boy_id = Column(Integer,Foreignkey("boy.id"))
    girl_id = Column(Integer.Foreignkey("girl.id"))
    
    
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:@127.0.0.1:3306/sqlalchemy?charset=utf8")

Base.metadata.create_all(engine)
2 ManyToMany__insert
from create_table_M2M import engine
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(engine)
db_session = Session()

from create_table_M2M import Girls,Boys
# 1 增加数据 - ralationship正向
girl_obj = Girls(name="Carrie")
girl_obj.g2b = [Boys(name="Gavin")]  # 多对多的关系这里用列表
db_session.add(girl_obj)
db_session.commit()
# 1 增加数据 - ralationship反向
boy_obj = Boys(name="Tom")
boy_obj.b2g = [Girls(name="罗y风"),Girls(name="谢y琳")]

db_session.add(boy_obj)
db_session.commit()
3 ManyToMany_select
from create_table_M2M import engine
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(engine)
db_session = Session()

from create_table_M2M import Girls,Boys
# 1 查询数据 - ralationship正向
girl_obj_list = db_session.query(Girls).all()  # 注意all()返回的是一个列表
for girl in girl_obj_list:
    for boy in girl.g2b:  # 注意girl.g2b返回的是列表
        print(girl.name, boy.name)

# 1 查询数据 - ralationship正向
boy_obj_list = db_session.query(Boy).all()  # 注意all()返回的是一个列表
for boy in boy_obj_list:
    for girl in boy.b2g:  # boy.b2g返回的是列表
        print(girl.name, boy.name)     


4 ManyToMany_select_高级操作
未完待续。。。

你可能感兴趣的:(SQLAlchemy之ManyToMany)