# 添加数据from sqlalchemy.orm import sessionmakerfrom create_table_ForeignKey import engine, Student, SchoolSession = 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 添加数据 - 反向relationshipsch_obj = School(name='TreasureShanghai')sch_obj.sch2stu = [Student(name='徐建-上海'), Student(name='徐建2-上海')]db_session.add(sch_obj)db_session.commit()db_session.close()#3.添加数据 - 正向relationshipstu_obj = Student(name='徐建3', stu2sch=School(name='TreasreShenzhen'))db_session.add(stu_obj)db_session.commit()db_session.close()
# 修改数据from sqlalchemy.orm import sessionmakerfrom create_table_ForeignKey import engine, Student, SchoolSession = 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 sessionmakerfrom create_table_ForeignKey import engine, Student, SchoolSession = 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 sessionmakerfrom create_table_ForeignKey import engine, Student, SchoolSession = 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])
posted on 2019-02-15 20:16 阅读( ...) 评论( ...)