Python3-sqlalchemy-orm 创建关联表带外键并查询数据
#-*-coding:utf-8-*-
#__author__ = "logan.xu" import sqlalchemy
from sqlalchemy import create_engine,func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,DATE
from sqlalchemy.orm import sessionmaker,relationship engine=create_engine("mysql+pymysql://root:12345678@localhost/news",encoding='utf-8',echo=True)
Base=declarative_base() class Student(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) class StudyRecord(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=relationship("Student",backref="my_study_record")
#
#def __repr__(self):
#return "<%s name:%s>" % (self.id,self.day)
def __repr__(self):
return "<%s day:%s status:%s>" % (self.id,self.day,self.status)
#---------------1.创建表-----------------#
Base.metadata.create_all(engine)
#---------------------------------------#
Session_class = sessionmaker(bind=engine) Session = Session_class()
#---------------2.写入数据-----------------#
s1=Student(name='Alex',register_date="2019-01-09")
s2=Student(name='Jack',register_date="2019-01-09")
s3=Student(name='Rain',register_date="2019-01-10")
s4=Student(name='Eric',register_date="2019-01-11")
s5=Student(name='John',register_date="2019-01-12")
#
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="NO",stu_id=2)
study_obj5=StudyRecord(day=1,status="NO",stu_id=2)
# ## 写入数据 并调用 study_record字段插入数据 为 Student数据
Session.add_all([s1,s2,s3,s4,s5,study_obj1,study_obj2,study_obj3,study_obj4,study_obj5])
#---------------------------------------#
#---------------3.查询数据-----------------#
# 取出student内的 内存对象
stu_obj = Session.query(Student).filter(Student.name=="Alex").first()
print(stu_obj.my_study_record)
#---------------------------------------#
# 执行事务 Session.commit()
/Users/drizzle/PycharmProjects/2018-12-03/venv/bin/python /Users/drizzle/PycharmProjects/2018-12-03/orm_fk.py
2019-01-08 18:30:00,061 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-01-08 18:30:00,061 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:30:00,063 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-01-08 18:30:00,063 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:30:00,065 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-01-08 18:30:00,065 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:30:00,066 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-01-08 18:30:00,066 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:30:00,069 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-01-08 18:30:00,069 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:30:00,069 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-01-08 18:30:00,069 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:30:00,070 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4)
COLLATE utf8mb4_bin AS anon_1
2019-01-08 18:30:00,070 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:30:00,071 INFO sqlalchemy.engine.base.Engine DESCRIBE `student`
2019-01-08 18:30:00,071 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:30:00,073 INFO sqlalchemy.engine.base.Engine DESCRIBE `study_record`
2019-01-08 18:30:00,073 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:30:00,080 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-01-08 18:30:00,081 INFO sqlalchemy.engine.base.Engine INSERT INTO student (name, register_date) VALUES (%(name)s, %(register_date)s)
2019-01-08 18:30:00,081 INFO sqlalchemy.engine.base.Engine {'name': 'Alex', 'register_date': '2019-01-09'}
2019-01-08 18:30:00,082 INFO sqlalchemy.engine.base.Engine INSERT INTO student (name, register_date) VALUES (%(name)s, %(register_date)s)
2019-01-08 18:30:00,082 INFO sqlalchemy.engine.base.Engine {'name': 'Jack', 'register_date': '2019-01-09'}
2019-01-08 18:30:00,082 INFO sqlalchemy.engine.base.Engine INSERT INTO student (name, register_date) VALUES (%(name)s, %(register_date)s)
2019-01-08 18:30:00,082 INFO sqlalchemy.engine.base.Engine {'name': 'Rain', 'register_date': '2019-01-10'}
2019-01-08 18:30:00,083 INFO sqlalchemy.engine.base.Engine INSERT INTO student (name, register_date) VALUES (%(name)s, %(register_date)s)
2019-01-08 18:30:00,083 INFO sqlalchemy.engine.base.Engine {'name': 'Eric', 'register_date': '2019-01-11'}
2019-01-08 18:30:00,083 INFO sqlalchemy.engine.base.Engine INSERT INTO student (name, register_date) VALUES (%(name)s, %(register_date)s)
2019-01-08 18:30:00,083 INFO sqlalchemy.engine.base.Engine {'name': 'John', 'register_date': '2019-01-12'}
2019-01-08 18:30:00,084 INFO sqlalchemy.engine.base.Engine INSERT INTO study_record (day, status, stu_id) VALUES (%(day)s, %(status)s, %(stu_id)s)
2019-01-08 18:30:00,084 INFO sqlalchemy.engine.base.Engine {'day': 1, 'status': 'Yes', 'stu_id': 1}
2019-01-08 18:30:00,085 INFO sqlalchemy.engine.base.Engine INSERT INTO study_record (day, status, stu_id) VALUES (%(day)s, %(status)s, %(stu_id)s)
2019-01-08 18:30:00,085 INFO sqlalchemy.engine.base.Engine {'day': 2, 'status': 'NO', 'stu_id': 1}
2019-01-08 18:30:00,085 INFO sqlalchemy.engine.base.Engine INSERT INTO study_record (day, status, stu_id) VALUES (%(day)s, %(status)s, %(stu_id)s)
2019-01-08 18:30:00,085 INFO sqlalchemy.engine.base.Engine {'day': 3, 'status': 'Yes', 'stu_id': 1}
2019-01-08 18:30:00,086 INFO sqlalchemy.engine.base.Engine INSERT INTO study_record (day, status, stu_id) VALUES (%(day)s, %(status)s, %(stu_id)s)
2019-01-08 18:30:00,086 INFO sqlalchemy.engine.base.Engine {'day': 1, 'status': 'NO', 'stu_id': 2}
2019-01-08 18:30:00,086 INFO sqlalchemy.engine.base.Engine INSERT INTO study_record (day, status, stu_id) VALUES (%(day)s, %(status)s, %(stu_id)s)
2019-01-08 18:30:00,086 INFO sqlalchemy.engine.base.Engine {'day': 1, 'status': 'NO', 'stu_id': 2}
2019-01-08 18:30:00,088 INFO sqlalchemy.engine.base.Engine SELECT student.id AS student_id, student.name AS student_name, student.register_date
AS student_register_date
FROM student
WHERE student.name = %(name_1)s
LIMIT %(param_1)s
2019-01-08 18:30:00,088 INFO sqlalchemy.engine.base.Engine {'name_1': 'Alex', 'param_1': 1}
2019-01-08 18:30:00,090 INFO sqlalchemy.engine.base.Engine SELECT study_record.id AS study_record_id, study_record.day AS study_record_day,
study_record.status AS study_record_status, study_record.stu_id AS study_record_stu_id
FROM study_record
WHERE %(param_1)s = study_record.stu_id
2019-01-08 18:30:00,090 INFO sqlalchemy.engine.base.Engine {'param_1': 1}
[<2 day:1 status:Yes>, <3 day:2 status:NO>, <4 day:3 status:Yes>, <7 day:1 status:Yes>, <8 day:2 status:NO>, <9 day:3 status:Yes>,
<12 day:1 status:Yes>, <13 day:2 status:NO>, <14 day:3 status:Yes>]
2019-01-08 18:30:00,091 INFO sqlalchemy.engine.base.Engine COMMIT Process finished with exit code 0
可以在study_record 反查student表信息 #-*-coding:utf-8-*-
#__author__ = "logan.xu" import sqlalchemy
from sqlalchemy import create_engine,func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,DATE
from sqlalchemy.orm import sessionmaker,relationship engine=create_engine("mysql+pymysql://root:12345678@localhost/news",encoding='utf-8',echo=True)
Base=declarative_base() class Student(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) class StudyRecord(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=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)
#---------------------------------------# Session_class = sessionmaker(bind=engine)
Session = Session_class() #---------------2.写入数据-----------------# s1=Student(name='Alex',register_date="2019-01-09")
s2=Student(name='Jack',register_date="2019-01-09")
s3=Student(name='Rain',register_date="2019-01-10")
s4=Student(name='Eric',register_date="2019-01-11")
s5=Student(name='John',register_date="2019-01-12")
#
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="NO",stu_id=2)
study_obj5=StudyRecord(day=1,status="NO",stu_id=2)
# ## 写入数据 并调用 study_record字段插入数据 为 Student数据
Session.add_all([s1,s2,s3,s4,s5,study_obj1,study_obj2,study_obj3,study_obj4,study_obj5]) #---------------------------------------# #---------------3.查询数据-----------------# # 取出student内的 内存对象
stu_obj = Session.query(Student).filter(Student.name=="Alex").first()
print(stu_obj.my_study_record) #---------------------------------------# # 执行事务
Session.commit()
/Users/drizzle/PycharmProjects/2018-12-03/venv/bin/python /Users/drizzle/PycharmProjects/2018-12-03/orm_fk.py
2019-01-08 18:35:46,521 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-01-08 18:35:46,522 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:35:46,523 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-01-08 18:35:46,523 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:35:46,525 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-01-08 18:35:46,525 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:35:46,526 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-01-08 18:35:46,526 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:35:46,529 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-01-08 18:35:46,529 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:35:46,529 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-01-08 18:35:46,530 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:35:46,530 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4)
COLLATE utf8mb4_bin AS anon_1
2019-01-08 18:35:46,530 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:35:46,531 INFO sqlalchemy.engine.base.Engine DESCRIBE `student`
2019-01-08 18:35:46,531 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:35:46,533 INFO sqlalchemy.engine.base.Engine DESCRIBE `study_record`
2019-01-08 18:35:46,533 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 18:35:46,541 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-01-08 18:35:46,542 INFO sqlalchemy.engine.base.Engine INSERT INTO student (name, register_date) VALUES (%(name)s, %(register_date)s)
2019-01-08 18:35:46,542 INFO sqlalchemy.engine.base.Engine {'name': 'Alex', 'register_date': '2019-01-09'}
2019-01-08 18:35:46,543 INFO sqlalchemy.engine.base.Engine INSERT INTO student (name, register_date) VALUES (%(name)s, %(register_date)s)
2019-01-08 18:35:46,543 INFO sqlalchemy.engine.base.Engine {'name': 'Jack', 'register_date': '2019-01-09'}
2019-01-08 18:35:46,544 INFO sqlalchemy.engine.base.Engine INSERT INTO student (name, register_date) VALUES (%(name)s, %(register_date)s)
2019-01-08 18:35:46,544 INFO sqlalchemy.engine.base.Engine {'name': 'Rain', 'register_date': '2019-01-10'}
2019-01-08 18:35:46,544 INFO sqlalchemy.engine.base.Engine INSERT INTO student (name, register_date) VALUES (%(name)s, %(register_date)s)
2019-01-08 18:35:46,544 INFO sqlalchemy.engine.base.Engine {'name': 'Eric', 'register_date': '2019-01-11'}
2019-01-08 18:35:46,545 INFO sqlalchemy.engine.base.Engine INSERT INTO student (name, register_date) VALUES (%(name)s, %(register_date)s)
2019-01-08 18:35:46,545 INFO sqlalchemy.engine.base.Engine {'name': 'John', 'register_date': '2019-01-12'}
2019-01-08 18:35:46,546 INFO sqlalchemy.engine.base.Engine INSERT INTO study_record (day, status, stu_id) VALUES (%(day)s, %(status)s, %(stu_id)s)
2019-01-08 18:35:46,546 INFO sqlalchemy.engine.base.Engine {'day': 1, 'status': 'Yes', 'stu_id': 1}
2019-01-08 18:35:46,547 INFO sqlalchemy.engine.base.Engine INSERT INTO study_record (day, status, stu_id) VALUES (%(day)s, %(status)s, %(stu_id)s)
2019-01-08 18:35:46,547 INFO sqlalchemy.engine.base.Engine {'day': 2, 'status': 'NO', 'stu_id': 1}
2019-01-08 18:35:46,547 INFO sqlalchemy.engine.base.Engine INSERT INTO study_record (day, status, stu_id) VALUES (%(day)s, %(status)s, %(stu_id)s)
2019-01-08 18:35:46,547 INFO sqlalchemy.engine.base.Engine {'day': 3, 'status': 'Yes', 'stu_id': 1}
2019-01-08 18:35:46,548 INFO sqlalchemy.engine.base.Engine INSERT INTO study_record (day, status, stu_id) VALUES (%(day)s, %(status)s, %(stu_id)s)
2019-01-08 18:35:46,548 INFO sqlalchemy.engine.base.Engine {'day': 1, 'status': 'NO', 'stu_id': 2}
2019-01-08 18:35:46,548 INFO sqlalchemy.engine.base.Engine INSERT INTO study_record (day, status, stu_id) VALUES (%(day)s, %(status)s, %(stu_id)s)
2019-01-08 18:35:46,548 INFO sqlalchemy.engine.base.Engine {'day': 1, 'status': 'NO', 'stu_id': 2}
2019-01-08 18:35:46,550 INFO sqlalchemy.engine.base.Engine SELECT student.id AS student_id, student.name AS student_name, student.register_date AS student_register_date
FROM student
WHERE student.name = %(name_1)s
LIMIT %(param_1)s
2019-01-08 18:35:46,550 INFO sqlalchemy.engine.base.Engine {'name_1': 'Alex', 'param_1': 1}
2019-01-08 18:35:46,552 INFO sqlalchemy.engine.base.Engine SELECT study_record.id AS study_record_id, study_record.day AS study_record_day,
study_record.status AS study_record_status, study_record.stu_id AS study_record_stu_id
FROM study_record
WHERE %(param_1)s = study_record.stu_id
2019-01-08 18:35:46,552 INFO sqlalchemy.engine.base.Engine {'param_1': 1}
[<Alex day:1 status:Yes>, <Alex day:2 status:NO>, <Alex day:3 status:Yes>, <Alex day:1 status:Yes>, <Alex day:2 status:NO>,
<Alex day:3 status:Yes>, <Alex day:1 status:Yes>, <Alex day:2 status:NO>, <Alex day:3 status:Yes>, <Alex day:1 status:Yes>,
<Alex day:2 status:NO>, <Alex day:3 status:Yes>]
2019-01-08 18:35:46,553 INFO sqlalchemy.engine.base.Engine COMMIT Process finished with exit code 0
Python3-sqlalchemy-orm 创建关联表带外键并查询数据的更多相关文章
- Python3-sqlalchemy-orm 创建关联表带外键并插入数据
#-*-coding:utf-8-*- #__author__ = "logan.xu" import sqlalchemy from sqlalchemy import crea ...
- Python3-sqlalchemy-orm 创建多表关联表带外键
#-*-coding:utf-8-*- #__author__ = "logan.xu" import sqlalchemy from sqlalchemy import crea ...
- 《Entity Framework 6 Recipes》中文翻译系列 (37) ------ 第六章 继承与建模高级应用之独立关联与外键关联
翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 6-13 在基类中应用条件 问题 你想从一个已存在的模型中的实体派生一个新的实体, ...
- 数据库的SQL语句创建和主外键删除操作
create table UserType ( Id ,), Name nvarchar() not null ) go create table UserInfo ( Id ,), LoginPwd ...
- mysql数据库:分表、多表关联、外键约束、级联操作
一.分表.外键.级联.多对一 二.多对多 三.一对一 一.分表.外键.级联.多对一 将部门数据与员工数据放到同一张表中会造成 数据重复 结构混乱 扩展维护性差 需要分表 create table de ...
- 003--PowerDesigner创建索引与外键
PowerDesigner创建索引与外键 一.创建索引 双击Table->Columns->创建索引 Step1:双击Table Step2:选择Columns->创建索引 弹出如下 ...
- SQLSERVER清空(Truncate)被外键引用的数据表
前言:我们知道SQLSERVER清空数据表有两种方式Delete和Truncate,当然两者的不同大家也都知道(不清楚的可以MSDN).不过这个错误“Cannot truncate table be ...
- Django ORM - 001 - 外键表查询主表信息
开始用Django做web开发,我想大家都会遇到同样的问题,那就是如何高效快速的查询需要的数据,MVC都很简单,但是ORM折腾起来就有些费时间,我准备好好研究下Django ORM,所以会有一个系列的 ...
- 使用Navicat V8.0创建数据库,外键出现错误ERROR 1005: Can’t create table (errno: 121)
ERROR 1005: Can't create table (errno: 121) errno 121 means a duplicate key error. Probably the tabl ...
随机推荐
- POJ2482 Stars in Your Window 题解
Fleeting time does not blur my memory of you. Can it really be 4 years since I first saw you? I stil ...
- Windows Server创建域控制器
推荐选择系统镜像为windows server2016(2019有诡异的bug不能安装域控.) 1.本地域安装设置 (1)连接到windows server2016 打开服务器管理器(Server M ...
- Ubuntu Server连接Wi-Fi
本文将介绍Ubuntu Server如何通过命令行使用wpa_supplicant连接Wi-Fi 环境 Ubuntu Server 20.04(64位) wpasupplicant 配置 1. 安装 ...
- tomcat与springmvc 结合 之---第16篇 servlet如何解析成员变量和DispatcherServlet如何解析
writedby 张艳涛,用了两个星期将深入刨析tomcat看完了,那么接下来该看什么呢?真是不知道,知识这东西上一个月看的jvm,锁.多线程并发 又都忘了.... tomcat学完,我打算看spri ...
- 大都市meg DFS序
题目描述 在经济全球化浪潮的影响下,习惯于漫步在清晨的乡间小路的邮递员Blue Mary也开始骑着摩托车传递邮件了.不过,她经常回忆起以前在乡间漫步的情景.昔日,乡下有依次编号为1..n的n个小村庄, ...
- 使用Fileupload完成文件的上传下载
目录 使用Fileupload完成文件的上传下载 为什么需要进行文件上传下载? 引入jar包 文件上传 注意事项 编写一个简单的文件上传jsp页面 编写Servlet Student类用于封装数据,后 ...
- 大数据开发-Go-数组,切片
new()和make的区别 二者看起来没什么区别,但是他们的行为不同,分别适用于不同的类型 new (T) 为每个新的类型 T 分配一片内存,初始化为 0 并且返回类型为 * T 的内存地址:这种方法 ...
- requests 上件中文文件名报错解决方案
这几天在用wxpy写机器人,在调用里面的上传文件接口的时候,一直报错.经过排查后,发现是不支持中文文件名:在群里问了下作者后才知道是requests惹的祸,默认requests用的是unicode来处 ...
- css文件编码
当css文件的编码
- 从事 Android应用开发4年有余,现在工资7500。很不爽!怎么办?
最近到某论坛看到一个帖子: 坐标北京,在一个公司从事android应用开发4年有余(毕业至今没换过公司).公司利润越来越大,工资却每年长1000,如今才到7500.琢磨着换工作,又不想扔下这四年来逐步 ...