sqlalchemy操作—-外键关联,relationship

...

#!_*_coding:utf-8_*_#__author__:"Alex huang"import sqlalchemyfrom sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column,Integer,String,ForeignKeyfrom sqlalchemy.orm import relationshipengine = create_engine("mysql+pymysql://hrg:123@192.168.80.100:3306/test",encoding=‘utf8‘)Base = declarative_base() #生成orm基类class students(Base): __tablename__ = ‘students‘ #表名 id = Column(Integer, primary_key=True) name = Column(String(32)) password = Column(String(64)) def __repr__(self): return "id:%s name:%s" %(self.id,self.name)class studyrecord(Base): __tablename__ = ‘studyrecord‘ #表名 id = Column(Integer, primary_key=True) day = Column(String(32)) status = Column(String(32)) stu_id = Column(Integer,ForeignKey("students.id")) #创建外键 students = relationship("students",backref="my_studyrecord") #创建关系,是在内存中映射的,没有实际创建表, #backref回调引用,students表可以通过my_studyrecord来引用studyrecord的数据 def __repr__(self): return "%s day:%s status:%s" %(self.students.name,self.day,self.status)Base.metadata.create_all(engine) #创建表Session_class = sqlalchemy.orm.session.sessionmaker(bind=engine) # 创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例Session = Session_class() # 生成session实例##插入 第一次运行先插入数据# s1 = students(name=‘hrg‘,password=‘111‘)# s2 = students(name=‘keke‘,password=‘122‘)# s3 = students(name=‘tom‘,password=‘333‘)# r1 = studyrecord(day=‘1‘,status=‘yes‘,stu_id=‘1‘)# r2 = studyrecord(day=‘1‘,status=‘yes‘,stu_id=‘2‘)# r3= studyrecord(day=‘2‘,status=‘no‘,stu_id=‘1‘)# r4 = studyrecord(day=‘3‘,status=‘yes‘,stu_id=‘1‘)# r5 = studyrecord(day=‘3‘,status=‘yes‘,stu_id=‘2‘)## Session.add_all([s1,s2,s3,r1,r2,r3,r4,r5])# Session.commit()data = Session.query(students).filter(students.name==‘hrg‘).first() #先students表里名称为hrg的第一条记录print(data.my_studyrecord) #打印hrg在studyrecord中的相关记录

  ...

相关文章