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])

 

上一篇:每天凌晨 2:00 将 mysql 数据库 testdb ,备份到文件中。


下一篇:[Aaronyang] 写给自己的WPF4.5 笔记9[复杂数据处理三步曲,数据展示ListView泪奔2/3]