创建外键关联 并通过relationship 互相调用

如图:

Python sqlalchemy orm 外键关联-LMLPHP

实现代码:

import sqlalchemy

# 调用链接数据库
from sqlalchemy import create_engine
# 调用基类Base
from sqlalchemy.ext.declarative import declarative_base
# 调用Column创建字段 加类型
from sqlalchemy import Column, Integer, String,DATE,ForeignKey
# 调用操作链接,反查
from sqlalchemy.orm import sessionmaker,relationship # create_engine 链接数据库 mysql+pymysql:链接对象//用户名:密码@主机/DB
# encoding='utf-8' 链接字符集 ,echo=True 把所有信息打印出来
engine = create_engine("mysql+pymysql://root:[email protected]/xiang",encoding='utf-8',
#echo=True
) # 生成orm基类
Base = declarative_base() class Student(Base):
__tablename__ = "student" # 设置id为主键
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) class StudyRecord(Base):
__tablename__ = "study_record" # 设置id为主键
id = Column(Integer,primary_key=True)
day = Column(Integer,nullable=False)
status = Column(String(32),nullable=False) # 将student表的id字段 设置为外键
stu_id = Column(Integer,ForeignKey("student.id")) # -允许你在Student表里通过backref字段反向查出所有它在表里的关联项-
# study_record表 通过student字段查找Student表内所有字段
# student表 通过my_study_record来访问study_record表内字段
# 注:relationship是orm自己通过在内存中类对象关联实现。
student = relationship("Student", backref="my_study_record") def __repr__(self):
return "<%s day:%s status:%s>" %(self.student.name,self.day,self.status) #---------------1.创建表-----------------#
# 创建表结构
# Base.metadata.create_all(engine)
#---------------------------------------# # bind=engine 绑定engine socket实例
Session_class = sessionmaker(bind=engine) # 生成session实例,如同pymysql内的cursor
Session = Session_class() #---------------2.插入数据-----------------# # Student 创建插入数据
# s1 = Student(name="kevin",register_date="2014-05-21")
# s2 = Student(name="Jack",register_date="2014-05-22")
# s3 = Student(name="Rain",register_date="2014-05-23")
# s4 = Student(name="Eric",register_date="2014-05-24") # StudyRecord 创建插入数据
# study_obj1 = StudyRecord(day=1,status="YES",stu_id=1)
# study_obj2 = StudyRecord(day=2,status="NO",stu_id=1)
# study_obj3 = StudyRecord(day=3,status="YES",stu_id=1)
# study_obj4 = StudyRecord(day=1,status="YES",stu_id=2) # 批量插入字段数据
# Session.add_all([s1,s2,s3,s4,study_obj1,study_obj2,study_obj3,study_obj4,])
#---------------------------------------# #---------------3.查看数据-----------------#
# 指定查看"kevin"学员
stu_obj = Session.query(Student).filter(Student.name=="kevin").first()
print(stu_obj.my_study_record)
#---------------------------------------# # 执行事务
Session.commit()
05-06 08:24