# 添加数据 from sqlalchemy.orm import sessionmaker from create_table_ForeignKey import engine, Student, School Session = sessionmaker(engine) db_session = Session() # 插入数据 sch_obj = School(name='Treasure') db_session.add(sch_obj) db_session.commit() sch = db_session.query(School).filter(School.name == 'Treasure').first() stu_obj = Student(name='徐建', school_id=sch.id) db_session.add(stu_obj) db_session.commit() db_session.close() #2 添加数据 - 反向relationship sch_obj = School(name='TreasureShanghai') sch_obj.sch2stu = [Student(name='徐建-上海'), Student(name='徐建2-上海')] db_session.add(sch_obj) db_session.commit() db_session.close() #3.添加数据 - 正向relationship stu_obj = Student(name='徐建3', stu2sch=School(name='TreasreShenzhen')) db_session.add(stu_obj) db_session.commit() db_session.close()
# 修改数据 from sqlalchemy.orm import sessionmaker from create_table_ForeignKey import engine, Student, School Session = sessionmaker(engine) db_session = Session() sch = db_session.query(School).filter(School.name == 'TreasureShanghai').first() db_session.query(Student).filter(Student.school_id == sch.id).delete() db_session.commit() db_session.close()
# 修改数据 from sqlalchemy.orm import sessionmaker from create_table_ForeignKey import engine, Student, School Session = sessionmaker(engine) db_session = Session() sch = db_session.query(School).filter(School.name == 'Treasure').first() db_session.query(Student).filter(Student.name == '徐建3').update({'school_id':sch.id}) db_session.commit() db_session.close()
# 查询数据 from sqlalchemy.orm import sessionmaker from create_table_ForeignKey import engine, Student, School Session = sessionmaker(engine) db_session = Session() # 查询数据 relationship 正向 stu = db_session.query(Student).all() for row in stu: print(row.id, row.name, row.stu2sch.name) # 查询数据 relationship 反向 sch = db_session.query(School).all() for row in sch: print(row.id, row.name, [i.name for i in row.sch2stu])