sqlalchemy 外键
生活随笔
收集整理的這篇文章主要介紹了
sqlalchemy 外键
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
建表
from sqlalchemy.ext.declarative import declarative_base Base = declarative_base()from sqlalchemy import Column,INT,VARCHAR,ForeignKey from sqlalchemy.orm import relationshipclass student(Base):__tablename__='student'id=Column(INT,primary_key=True)name=Column(VARCHAR(64))school_id=Column(INT,ForeignKey('school.id'))#stu2sch=relationship('school',backref='sch2stu') #本條在采用relationship插入數據是寫入class school(Base):__tablename__='school'id=Column(INT,primary_key=True)name = Column(VARCHAR(64))from sqlalchemy import create_engineengine=create_engine('mysql+pymysql://root:941015@192.168.50.67:3306/sqlarchm?charset=utf8')Base.metadata.create_all(engine) # Base.metadata.drop_all(engine)插入數據:
from sqlalchemy.orm import sessionmaker from create_table_foreignkey import engine,school,studentSession=sessionmaker(engine) db_session=Session()#笨方法 # sch_obj=school(name='dongnanya') # db_session.add(sch_obj) # db_session.commit() # # sch_obj=db_session.query(school).filter(school.name=='dongnanya').first() # student_obj=student(name='chaochao',school_id=sch_obj.id) # db_session.add(student_obj) # db_session.commit() # db_session.close()#利用relationship -正向# stu_obj = student(name='LUCIFER',stu2sch=school(name='dongbeiya')) # # db_session.add(stu_obj) # db_session.commit() # db_session.close()#利用relationship -反向 sch_obj=school(name='xxy') sch_obj.sch2stu=[student(name='beibei'),student(name='huahua')] db_session.add(sch_obj)db_session.commit()?查:
from sqlalchemy.orm import sessionmaker from create_table_foreignkey import engine,student,schoolSession=sessionmaker(engine) db_session=Session()#查詢 笨 # sch_obj=db_session.query(school).filter(school.name=='dongbeiya').first() # # stu_obj=db_session.query(student).filter(student.school_id==sch_obj.id).first() # # print(stu_obj.name,sch_obj.name)#relationship 正向# stu_obj=db_session.query(student).filter(student.name=='LUCIFER').first() # print(stu_obj.stu2sch.name,stu_obj.name)#relationship 反向 sch_obj=db_session.query(school).all() for row in sch_obj:for stu in row.sch2stu:print(row.name,stu.name)刪除和更新 沒有簡單操作
轉載于:https://www.cnblogs.com/Lucifer77/p/10776438.html
總結
以上是生活随笔為你收集整理的sqlalchemy 外键的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设置mac笔记本为固定ip
- 下一篇: Java相关面试题总结+答案(一)