数据库
首页 > 数据库> > SQLAlchemy的使用---M2M增删改查

SQLAlchemy的使用---M2M增删改查

作者:互联网

from sqlalchemy.orm import sessionmaker
from sqlalchemy_M2M import engine, Girls, Boys

Session = sessionmaker(engine)
db_session = Session()

# 1.通过Boy添加Girl relationship 反向
boy = Boys(name='XJ')
boy.boy2girl = [Girls(name='G1'), Girls(name='G2')]
db_session.add(boy)
db_session.commit()
db_session.close()

# 2.通过Gril添加Boy和Hotel的数据 relationship 正向
girl = Girls(name='G3', girl2boy=[Boys(name='B1'), Boys(name='B2')])
db_session.add(girl)
db_session.commit()
db_session.close()

# 3.查询 relationship 正向
g_list = db_session.query(Girls).all()
for row in g_list:
    print(row.id, row.name, [boy.name for boy in row.girl2boy])

# 4.查询 relationship 反向
b_list = db_session.query(Boys).all()
for row in b_list:
    print(row.id, row.name, [girl.name for girl in row.boy2girl])

 

标签:SQLAlchemy,name,Boys,改查,db,M2M,session,Girls,row
来源: https://www.cnblogs.com/Treasuremy/p/10385712.html