sqlalchemy 多对多创建表,以及添加查询操作

一,多对多表的创建:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy import Column,INT,VARCHAR,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")  #建立多对多关系

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)
    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:dd112211@127.0.0.1:3306/sqlalchemy?charset=utf8")

Base.metadata.create_all(engine)

1,新增数据

# 1.增加数据 - relationship 正向
girl_obj = Girls(name="妹子1")
girl_obj.g2b = [Boys(name="哥哥1"),Boys(name="哥哥2")]  #查Girl类中backref="b2g"
db_session.add(girl_obj)
db_session.commit()
# 2.增加数据 - relationship 反向
boy_obj = Boys(name="关关")
boy_obj.b2g = [Girls(name="美女1"),Girls(name="美女2")]
db_session.add(boy_obj)
db_session.commit()

图说:
在这里插入图片描述

2,查询

正向-- g2b

girl_obj_list = db_session.query(Girls).all()
for girl_obj in girl_obj_list:
    for boy in girl_obj.g2b:
        print(girl_obj.name,boy.name)

反向-- b2g

boy_obj_list = db_session.query(Boys).all()
for boy in boy_obj_list:
    for girl in boy.b2g:
        print(girl.name,boy.name)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值