Flask中的的SQLAlchemy2
昨天更新了博客不知对各位职场的大佬有没有帮助,如果没有看到的请用小手狠狠地戳这里
Flask中的的SQLAlchemy
今天呢,我们来说一下多对多表的关系,知道不?开始之前我先说一个事,昨晚更新了博客之后我梦到一位女粉丝走到我面请轻轻的吻了我,啧啧啧,味可好了~~~~
1.多对多表关系
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from sqlalchemy import Column,Integer,String,ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Girls(Base): __tablename__ = 'girl' id = Column(Integer,primary_key=True) name = Column(String(32)) #表的关系 girl2boy = relationship("Boys",secondary = "hotel",backref = "boy2girl") class Boys(Base): __tablename__ = 'boy' id = Column(Integer,primary_key=True) name = Column(String(32)) class Hotel(Base): __tablename__='hotel' id = Column(Integer,primary_key=True) girl_id = Column(Integer,ForeignKey("girl.id")) boy_id = Column(Integer,ForeignKey("boy.id")) from sqlalchemy import create_engine #这里不懂得,戳紫色的字!! engine = create_engine("mysql+pymysql://root:614615@127.0.0.1:3306/day127?charset=utf8") Base.metadata.create_all(engine)
2.简单的操作
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#curd_M2M.py from sqlalchemy.orm import sessionmaker from SQL.curd_M2m import engine from SQL.curd_M2m import Boys,Girls,Hotel Session = sessionmaker(engine) db_session = Session() #t通过想Boy添加数据添加girl和hotel数据。relationship反向 boy = Boys(name="李志强") boy.boy2girl = [Girls(name="哇哈哈"),Girls(name="喜洋洋")] db_session.add(boy) db_session.commit() db_session.close() #t通过想Girl添加数据添加boy和hotel数据。relationship正向 girl_obj = Girls(name="李二短",girl2boy=[Boys(name="任二狗"),Boys(name="任梦")]) db_session.add(girl_obj) db_session.commit() db_session.close() # 查询 正向查询 ret = db_session.query(Girls).all() for girl in ret: for boy in girl.girl2boy: #这里说一下,注意表的结构,有很多的小的细节不注意就会报错,查到girl信息,再次遍历的时候注意girl.girl2boy,正向查询 print(girl.name , boy.name) # 查询 反向查询 ret = db_session.query(Boys).all() for boy in ret: for girl in boy.boy2girl: print(boy.name,girl.name)