sqlalchemy_外键连接表

importsqlalchemy
fromsqlalchemyimportcreate_engine#连接数据库
fromsqlalchemy.ext.declarativeimportdeclarative_base#orm基类
fromsqlalchemyimportColumn,Integer,String,DATE,ForeignKey#Column列
fromsqlalchemy.ormimportsessionmaker,relationship
engine=create_engine("MySQL+pymysql://root:123456@192.168.0.6/wupeiqi",
                     encoding='utf-8',echo=False)#连接数据库 echo=TRUE输出执行过程

base=declarative_base()# 生成基类

classStudent(base):
    __tablename__="student"
    
id=Column(Integer,primary_key=True)
    name=Column(String(32),nullable=False)
    register_date=Column(DATE,nullable=False)
    def__repr__(self):
        return"<%s name:%s>"%(self.id,self.name)

classStudyRecord(base):
    __tablename__="study_record"
    
id = Column(Integer,primary_key=True)
    day=Column(Integer,nullable=False)
    status=Column(String(32),nullable=False)
    stu_id=Column(Integer,ForeignKey('student.id'))#外键关联到student的id
    #StudyRecord通过student字段查询Student表里所有数据  在内存里建立relationship关系
    student=relationship("Student",backref="my_study_record")#允许你可以在student表里通过my_study_record字段反查Studyrecord所有数据
    def__repr__(self):
        return"<%s day:%s status:%s>"%(self.student.name,self.day,self.status)
base.metadata.create_all(engine)#创建表

#连接mysql
Session_class = sessionmaker(bind=engine)  # 创建与数据库的连接session class ,注意,这里返回给session的是个class,不是实例
session = Session_class()  # 生成session实例 session会话 类似cursor
'''
#插入数据
s1=Student(name="kobe",register_date="2017-05-16")
s2=Student(name="jack",register_date="2017-04-16")
s3=Student(name="duncon",register_date="2017-06-16")
s4=Student(name="Allen",register_date="2017-07-16")

record_1=StudyRecord(day=1,status="YES",stu_id=1)
record_2=StudyRecord(day=2,status="NO",stu_id=1)
record_3=StudyRecord(day=3,status="YES",stu_id=1)
record_4=StudyRecord(day=1,status="YES",stu_id=2)

session.add_all([s1,s2,s3,s4,record_1,record_2,record_3,record_4])
session.commit()
'''
#外键查询数据
stu_obj=session.query(Student).filter(Student.name=="kobe").first()
print(stu_obj.my_study_record)

创新互联建站主营独山网站建设的网络公司,主营网站建设方案,成都App定制开发,独山h5小程序开发搭建,独山网站营销推广欢迎独山等地区企业咨询


当前题目:sqlalchemy_外键连接表
浏览地址:http://myzitong.com/article/jdjgpo.html