突突突突突突

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
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])

 

posted on 2019-02-15 20:19  徐建0304  阅读(212)  评论(0编辑  收藏  举报