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 Customer(Base):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
name = Column(String(64)) # 以Address表id字段 设置两个外键
billing_address_id = Column(Integer, ForeignKey("address.id"))
shipping_address_id = Column(Integer, ForeignKey("address.id")) # relationship -允许你在Student表里通过backref字段反向查出所有它在表里的关联项-
# foreign_keys=绑定外键 多次relationship 反差会识别不出指定数据所以添加foreign_keys参数。
billing_address = relationship("Address",foreign_keys=[billing_address_id])
shipping_address = relationship("Address",foreign_keys=[shipping_address_id]) class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
street = Column(String(64))
city = Column(String(64))
state = Column(String(64)) # 返回一个可以用来表示对象的可打印字符串
def __repr__(self):
return self.street #---------------1.创建表-----------------#
# 创建表结构
Base.metadata.create_all(engine)
#---------------------------------------# # bind=engine 绑定engine socket实例
#Session_class = sessionmaker(bind=engine) # 生成session实例,如同pymysql内的cursor
#Session = Session_class() #---------------2.写入数据-----------------# # 写入数据
# addr1 = orm_fk.Address(street="Tiantongyuan",city="ChangPing",state="BJ")
# addr2 = orm_fk.Address(street="Wudaokou",city="Haidian",state="BJ")
# addr3 = orm_fk.Address(street="Yanjiao",city="Langfang",state="HB") # 插入数据
# Session.add_all([addr1,addr2,addr3]) # 写入数据 并调用 Address字段插入数据 为 Customer数据
# c1 = orm_fk.Customer(name="kevin",billing_address=addr1,shipping_address=addr2)
# c2 = orm_fk.Customer(name="Jack",billing_address=addr3,shipping_address=addr3) # 插入数据
# Session.add_all([c1,c2])
#---------------------------------------# #---------------3.查询数据-----------------# # 取出Customer内的 内存对象
#obj = Session.query(Customer).filter(Customer.name=="kevin").first() # 通过内存 调用第一行name字段数据,
# 调用billing_address对应外键id的对应数据,
# 调用obj.shipping_address对应外键id的对应数据。
#print(obj.name,obj.billing_address,obj.shipping_address)
#---------------------------------------# # 执行事务
#Session.commit()
/Users/drizzle/PycharmProjects/2018-12-03/venv/bin/python /Users/drizzle/PycharmProjects/2018-12-03/test_1/orm_api.py
2019-01-08 19:07:49,013 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-01-08 19:07:49,013 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:07:49,015 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-01-08 19:07:49,015 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:07:49,017 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-01-08 19:07:49,017 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:07:49,018 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-01-08 19:07:49,018 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:07:49,020 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-01-08 19:07:49,020 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:07:49,021 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-01-08 19:07:49,021 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:07:49,022 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4)
COLLATE utf8mb4_bin AS anon_1
2019-01-08 19:07:49,022 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:07:49,023 INFO sqlalchemy.engine.base.Engine DESCRIBE `customer`
2019-01-08 19:07:49,023 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:07:49,024 INFO sqlalchemy.engine.base.Engine DESCRIBE `address`
2019-01-08 19:07:49,024 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:07:49,030 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-01-08 19:07:49,031 INFO sqlalchemy.engine.base.Engine INSERT INTO address (street, city, state) VALUES (%(street)s, %(city)s, %(state)s)
2019-01-08 19:07:49,031 INFO sqlalchemy.engine.base.Engine {'street': 'tiantongyuan', 'city': 'changping', 'state': 'BJ'}
2019-01-08 19:07:49,032 INFO sqlalchemy.engine.base.Engine INSERT INTO address (street, city, state) VALUES (%(street)s, %(city)s, %(state)s)
2019-01-08 19:07:49,032 INFO sqlalchemy.engine.base.Engine {'street': 'wudaokou', 'city': 'haidian', 'state': 'BJ'}
2019-01-08 19:07:49,033 INFO sqlalchemy.engine.base.Engine INSERT INTO address (street, city, state) VALUES (%(street)s, %(city)s, %(state)s)
2019-01-08 19:07:49,033 INFO sqlalchemy.engine.base.Engine {'street': 'yanjiao', 'city': 'langfang', 'state': 'BJ'}
2019-01-08 19:07:49,034 INFO sqlalchemy.engine.base.Engine INSERT INTO customer (name, billing_address_id, shipping_address_id) VALUES (%(name)s,
%(billing_address_id)s, %(shipping_address_id)s)
2019-01-08 19:07:49,034 INFO sqlalchemy.engine.base.Engine {'name': 'Alex', 'billing_address_id': 1, 'shipping_address_id': 2}
2019-01-08 19:07:49,035 INFO sqlalchemy.engine.base.Engine INSERT INTO customer (name, billing_address_id, shipping_address_id) VALUES (%(name)s,
%(billing_address_id)s, %(shipping_address_id)s)
2019-01-08 19:07:49,035 INFO sqlalchemy.engine.base.Engine {'name': 'Jack', 'billing_address_id': 3, 'shipping_address_id': 3}
2019-01-08 19:07:49,035 INFO sqlalchemy.engine.base.Engine COMMIT Process finished with exit code 0
mysql> show tables;
+----------------+
| Tables_in_news |
+----------------+
| address |
| customer |
| student |
| study_record |
| user |
+----------------+
5 rows in set (0.00 sec) mysql> select * from customer;
+----+------+--------------------+---------------------+
| id | name | billing_address_id | shipping_address_id |
+----+------+--------------------+---------------------+
| 1 | Alex | 1 | 2 |
| 2 | Jack | 3 | 3 |
+----+------+--------------------+---------------------+
2 rows in set (0.00 sec) mysql> select * from address;
+----+--------------+-----------+-------+
| id | street | city | state |
+----+--------------+-----------+-------+
| 1 | tiantongyuan | changping | BJ |
| 2 | wudaokou | haidian | BJ |
| 3 | yanjiao | langfang | BJ |
+----+--------------+-----------+-------+
3 rows in set (0.00 sec)
#查询
#-*-coding:utf-8-*-
#__author__ = "logan.xu" from test_1 import orm_many_fk
from sqlalchemy.orm import sessionmaker Session_class=sessionmaker(bind=orm_many_fk.engine) #创建与数据库的链接
session= Session_class() #生成session实例 #cursor #addr1=orm_many_fk.Address(street="tiantongyuan",city="changping",state="BJ")
#addr2=orm_many_fk.Address(street="wudaokou",city="haidian",state="BJ")
#add#r3=orm_many_fk.Address(street="yanjiao",city="langfang",state="BJ")
#
#session.add_all([addr1,addr2,addr3])
#c1= orm_many_fk.Customer(name="Alex",billing_address=addr1,shipping_address=addr2)
#c2= orm_many_fk.Customer(name="Jack",billing_address=addr3,shipping_address=addr3) #session.add_all([c1,c2]) #查询
obj=session.query(orm_many_fk.Customer).filter(orm_many_fk.Customer.name=="alex").first()
print(obj.name,obj.billing_address,obj.shipping_address) session.commit()
/Users/drizzle/PycharmProjects/2018-12-03/venv/bin/python /Users/drizzle/PycharmProjects/2018-12-03/test_1/orm_api.py
2019-01-08 19:15:17,840 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-01-08 19:15:17,840 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:15:17,842 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-01-08 19:15:17,842 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:15:17,844 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-01-08 19:15:17,844 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:15:17,844 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-01-08 19:15:17,844 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:15:17,847 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-01-08 19:15:17,847 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:15:17,848 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-01-08 19:15:17,848 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:15:17,849 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4)
COLLATE utf8mb4_bin AS anon_1
2019-01-08 19:15:17,849 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:15:17,850 INFO sqlalchemy.engine.base.Engine DESCRIBE `customer`
2019-01-08 19:15:17,850 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:15:17,851 INFO sqlalchemy.engine.base.Engine DESCRIBE `address`
2019-01-08 19:15:17,851 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:15:17,857 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-01-08 19:15:17,858 INFO sqlalchemy.engine.base.Engine SELECT customer.id AS customer_id, customer.name AS customer_name,
customer.billing_address_id AS customer_billing_address_id, customer.shipping_address_id AS customer_shipping_address_id
FROM customer
WHERE customer.name = %(name_1)s
LIMIT %(param_1)s
2019-01-08 19:15:17,858 INFO sqlalchemy.engine.base.Engine {'name_1': 'alex', 'param_1': 1}
2019-01-08 19:15:17,859 INFO sqlalchemy.engine.base.Engine SELECT address.id AS address_id, address.street AS address_street,
address.city AS address_city, address.state AS address_state
FROM address
WHERE address.id = %(param_1)s
2019-01-08 19:15:17,860 INFO sqlalchemy.engine.base.Engine {'param_1': 1}
2019-01-08 19:15:17,861 INFO sqlalchemy.engine.base.Engine SELECT address.id AS address_id, address.street AS address_street,
address.city AS address_city, address.state AS address_state
FROM address
WHERE address.id = %(param_1)s
2019-01-08 19:15:17,861 INFO sqlalchemy.engine.base.Engine {'param_1': 2}
Alex tiantongyuan wudaokou
2019-01-08 19:15:17,862 INFO sqlalchemy.engine.base.Engine COMMIT Process finished with exit code 0
Python3-sqlalchemy-orm 创建多表关联表带外键的更多相关文章
- mysql数据库:分表、多表关联、外键约束、级联操作
一.分表.外键.级联.多对一 二.多对多 三.一对一 一.分表.外键.级联.多对一 将部门数据与员工数据放到同一张表中会造成 数据重复 结构混乱 扩展维护性差 需要分表 create table de ...
- 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 ...
- disable enable 所有其他表关联的外键
Disable: begin for i in (select constraint_name, table_name from user_constraints where constraint_n ...
- ORM创建多表以及多表的增删改查
一. 多表的创建 1. 一对一 在哪个表中设置都行,但是添加数据的时候需要现在没有外键的表中添加数据 models.OneToOneField(to="表名",to_field=& ...
- Springboot项目启动后自动创建多表关联的数据库与表的方案
文/朱季谦 在一些项目开发当中,存在这样一种需求,即开发完成的项目,在第一次部署启动时,需能自行构建系统需要的数据库及其对应的数据库表. 若要解决这类需求,其实现在已有不少开源框架都能实现自动生成数据 ...
- Python3-sqlalchemy-orm 联表查询-无外键关系
#-*-coding:utf-8-*- #__author__ = "logan.xu" import sqlalchemy from sqlalchemy import crea ...
- Django学习——Django测试环境搭建、单表查询关键字、神奇的双下划线查询(范围查询)、图书管理系统表设计、外键字段操作、跨表查询理论、基于对象的跨表查询、基于双下划线的跨表查询
Django测试环境搭建 ps: 1.pycharm连接数据库都需要提前下载对应的驱动 2.自带的sqlite3对日期格式数据不敏感 如果后续业务需要使用日期辅助筛选数据那么不推荐使用sqlite3 ...
- 《Entity Framework 6 Recipes》中文翻译系列 (37) ------ 第六章 继承与建模高级应用之独立关联与外键关联
翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 6-13 在基类中应用条件 问题 你想从一个已存在的模型中的实体派生一个新的实体, ...
随机推荐
- informix 数据库锁表分析和解决方法
一.前言 在联机事务处理(OLTP)的数据库应用系统中,多用户.多任务的并发性是系统最重要的技术指标之一.为了提高并发性,目前大部分RDBMS都采用加锁技术.然而由于现实环境的复杂性,使用加锁技术又不 ...
- Oracle12c至少开启的服务
如图,至少开启这两个服务才能运行
- Linux系统进入redis并查询值
1.进入redisredis-cli -h ip -p port2.查看具体信息info 3.得到redis中存储的所有key值KEYS *4.获取指定key值的value值get "key ...
- bootstrap table记录一下
$(function() { // 刷新 talbe function refresh() { $("#table").bootstrapTable('refresh'); } $ ...
- 某学院m3u8视频解密获取分析实战分享
[免责声明]本文来源于作者个人学习整理,仅供学习交流使用,不构成商业目的.所有资源均系本人个人学习或网络收集,仅提供一个展示.介绍.观摩学习的博文,不对其内容的准确性.可靠性.正当性.安全性.合法性等 ...
- MFC发送自定义消息
1.在窗口的头文件中声明: afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam); 2.在cpp的BEGIN_MESSAGE_MAP和EN ...
- 攻防世界逆向——game
攻防世界逆向:game wp 攻防世界逆向新手区的一道题目. 是一道windows的creak,动态调试打开是这样的: 题目说明是让屏幕上所有的图像都亮之后,会出现flag,看来应该是可以玩出来的. ...
- Quartz 实现同一辅助类 重复开启多任务
前言: 最近做一个项目,需要用到定时任务,第一就想到了Quartz,然后很开心的就实现了功能,但是后来发现一个问题,如果需要开启多个定时任务,需要写多个辅助类,而辅助类里面的功能基本差不多,这是我就想 ...
- JQuery常用属性操作,动画,事件绑定
jQuery 的属性操作 html() 它可以设置和获取起始标签和结束标签中的内容. 跟 dom 属性 innerHTML 一样. text() 它可以设置和获取起始标签和 ...
- Linux进程理解与实践(三)进程终止函数和exec函数族的使用
进程的几种终止方式(Termination) (1)正常退出 从main函数返回[return] 调用exit 调用_exit或者_Exit 最后一个线程从其启动处返回 从最后一个线程调用pthrea ...