python 之sqlalchemy many to many
# -*- coding: utf-8 -*-
"""
@author: zengchunyun
"""
from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey, Table
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine Base = declarative_base()
engine = create_engine('mysql+pymysql://root:123@127.0.0.1:3306/day11',echo=True) class Association(Base):
__tablename__ = 'association'
left_id = Column(Integer, ForeignKey("left.id"), primary_key=True)
right_id = Column(Integer, ForeignKey("right.id"), primary_key=True)
extra_data = Column(String(50))
child = relationship("Child", back_populates="parents")
parent = relationship("Parent", back_populates="children") class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True)
children = relationship("Association", back_populates='parent') class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
parents = relationship("Association", back_populates="child") Base.metadata.create_all(engine) DBSession = sessionmaker()
DBSession.configure(bind=engine)
session = DBSession() # 打开数据连接 # 插入数据方式一
# p = Parent()
# c = Child()
# a = Association(extra_data="ss")
# a.parent = p
# a.child = c
# 插入数据方式二
c = Child()
a = Association(extra_data='dd')
a.parent = Parent()
c.parents.append(a) # 插入数据方式三
# p = Parent()
# a = Association(extra_data="some data")
# a.child = Child()
# p.children.append(a)
#
# for assoc in p.children:
# print(assoc.extra_data)
# print(assoc.child) session.add(a)
session.commit()
第二种方式
上面的其它代码不变,只修改relationship关系,效果是一样的
class Association(Base):
__tablename__ = 'association'
left_id = Column(Integer, ForeignKey("left.id"), primary_key=True)
right_id = Column(Integer, ForeignKey("right.id"), primary_key=True)
extra_data = Column(String(50))
child = relationship("Child", backref="parents")
parent = relationship("Parent", backref="children") class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True) class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
第三种方式,完整版
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zengchunyun
"""
from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey, Table
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine Base = declarative_base()
engine = create_engine('mysql+pymysql://root:123@127.0.0.1:3306/day11',echo=True) class Association(Base):
__tablename__ = 'association'
left_id = Column(Integer, ForeignKey("left.id"), primary_key=True)
right_id = Column(Integer, ForeignKey("right.id"), primary_key=True)
extra_data = Column(String(50))
child = relationship("Child") class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True)
children = relationship("Association") class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True) Base.metadata.create_all(engine) DBSession = sessionmaker()
DBSession.configure(bind=engine)
session = DBSession() # 打开数据连接 p = Parent()
a = Association(extra_data='dasa')
a.child = Child()
p.children.append(a)
session.add(p) #注意,这里必须先添加p,否则关系映射不成功
session.add(a) #再添加a,记录就能添加成功了
session.commit()
以上三种方式最终效果是一样的,针对第三张表的写法还有另一种实现方式,通过Table创建,有时间再补上
many to many table形式
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zengchunyun
"""
from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey, Table
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine Base = declarative_base()
engine = create_engine('mysql+pymysql://root:123@127.0.0.1:3306/day11',echo=True) PC = Table("p_c", Base.metadata,
Column("left_id", Integer, ForeignKey("left.id")),
Column("right_id",Integer, ForeignKey("right.id"))
) class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True)
name = Column(String(22))
child = relationship("Child", secondary=PC) class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
name = Column(String(22)) Base.metadata.create_all(engine) DBSession = sessionmaker()
DBSession.configure(bind=engine)
session = DBSession() # 打开数据连接 p1 = Parent(name='zeng')
c1 = Child(name="haha")
p1.child.append(c1) # 只有存在relationship关系的对象才能通过append形式添加记录
# 或者p1.child = [c1]
session.add(p1)
session.commit()
Table形式二
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zengchunyun
"""
from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey, Table
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine Base = declarative_base()
engine = create_engine('mysql+pymysql://root:123@127.0.0.1:3306/day11',echo=True) PC = Table("p_c", Base.metadata,
Column("left_id", Integer, ForeignKey("left.id")),
Column("right_id",Integer, ForeignKey("right.id"))
) class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True)
name = Column(String(22))
child = relationship("Child", secondary=PC,
back_populates="parents") class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
name = Column(String(22))
parents = relationship("Parent", secondary=PC,
back_populates="child") Base.metadata.create_all(engine) DBSession = sessionmaker()
DBSession.configure(bind=engine)
session = DBSession() # 打开数据连接 # # 第一种数据插入方式
# p1 = Parent(name='zeng')
# c1 = Child(name="haha")
# p1.child.append(c1) # 只有存在relationship关系的对象才能通过append形式添加记录
# # 或者p1.child = [c1]
# session.add(p1)
# 第二种
# p1 = Parent(name='zeng')
# c1 = Child(name='haha')
# c1.parents.append(p1)
# session.add(c1)
# 第三种
# p1 = Parent(name='zeng')
# p1.child = [Child(name="hah")]
# session.add(p1)
# 第四种
p1 = Parent(name="zcy", child=[Child(name='sasa')])
session.add(p1)
session.commit() # 以上四种插入效果都是一样的
Table最后一种写法
PC = Table("p_c", Base.metadata,
Column("left_id", Integer, ForeignKey("left.id")),
Column("right_id",Integer, ForeignKey("right.id"))
) class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True)
name = Column(String(22))
child = relationship("Child", secondary=PC,
backref="parents") class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
name = Column(String(22))
以上几种Table形式多对多写法效果是一样的,只是在查询上有一定区别,
第二种table与第三种其实是完全一样的效果
python 之sqlalchemy many to many的更多相关文章
- 基于Python的SQLAlchemy的操作
安装 在Python使用SQLAlchemy的首要前提是安装相应的模块,当然作为python的优势,可以到python安装目录下的scripts下,同时按住shift+加上鼠标左键,从而在菜单中打开命 ...
- SQLAlchemy(1) -- Python的SQLAlchemy和ORM
Python的SQLAlchemy和ORM(object-relational mapping:对象关系映射) web编程中有一项常规任务就是创建一个有效的后台数据库.以前,程序员是通过写sql语句, ...
- python使用sqlalchemy连接pymysql数据库
python使用sqlalchemy连接mysql数据库 字数833 阅读461 评论0 喜欢1 sqlalchemy是python当中比较出名的orm程序. 什么是orm? orm英文全称objec ...
- python之SQLAlchemy
ORM介绍 orm英文全称object relational mapping,就是对象映射关系程序,简单来说我们类似python这种面向对象的程序来说一切皆对象,但是我们使用的数据库却都是关系型的,为 ...
- Python’s SQLAlchemy vs Other ORMs[转发 7] 比较结论
Comparison Between Python ORMs For each Python ORM presented in this article, we are going to list t ...
- Python’s SQLAlchemy vs Other ORMs[转发 6]SQLAlchemy
SQLAlchemy SQLAlchemy is an open source SQL toolkit and ORM for the Python programming language rele ...
- Python’s SQLAlchemy vs Other ORMs[转发 3]Django's ORM
Django's ORM Django is a free and open source web application framework whose ORM is built tightly i ...
- Python’s SQLAlchemy vs Other ORMs[转发 2]Storm
Storm Storm is a Python ORM that maps objects between one or more databases and Python. It allows de ...
- Python’s SQLAlchemy vs Other ORMs[转发 0]
原文地址:http://pythoncentral.io/sqlalchemy-vs-orms/ Overview of Python ORMs As a wonderful language, Py ...
- Python’s SQLAlchemy vs Other ORMs[转发 1]SQLObject
SQLObject SQLObject is a Python ORM that maps objects between a SQL database and Python. It is becom ...
随机推荐
- kindeditor在光标处插入编辑器外的数据
页面 <div class="form-group clearfix"> <label class="control-label col-sm-3 co ...
- C# BlockCollection
1.BlockCollection集合是一个拥有阻塞功能的集合,它就是完成了经典生产者消费者的算法功能. 它没有实现底层的存储结构,而是使用了IProducerConsumerCollection接口 ...
- ETL简介
1.ETL的定义 ETL分别是“Extract”.“ Transform” .“Load”三个单词的首字母缩写也就是“抽取”.“转换”.“装载”,但我们日常往往简称其为数据抽取. ETL是BI/DW( ...
- [NHibernate]关联映射
系列文章 [Nhibernate]体系结构 [NHibernate]ISessionFactory配置 [NHibernate]持久化类(Persistent Classes) [NHibernate ...
- 媒体查询判断ipad和iPhone各版本
/* 判断ipad */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px){ /* s ...
- PHP exec/system启动windows应用程序,执行.bat批处理,执行cmd命令
exec 或者 system 都可以调用cmd 的命令 直接上代码: <?php /** 打开windows的计算器 */ exec('start C:WindowsSystem32calc.e ...
- nth-of-type
ul li{ height:53px; line-height:53px; border-top:1px solid #e5e5e5; display:block;color:#444; } ...
- T-SQL 语句的优化
SQL调优. 1.索引是数据库调优的最根本的优化方法.聚簇索引.非聚簇索引. 聚簇索引:物理序与索引顺序相同.(只能有一个) 非聚簇索引:物理顺序与索引顺序不相同. 2.调整WHERE 子句中的连接顺 ...
- Windows中explorer(图形壳)
explorer是Windows程序管理器或者文件资源管理器. 用于管理Windows图形壳.(桌面和文件管理.) 删除该程序会导致Windows图形界面无法使用. explorer.exe进程是微软 ...
- Websocket通讯简析
什么是Websocket Websocket是一种全新的协议,不属于HTTP无状态协议,协议名为"ws",这意味着一个Websocket连接地址会是这样的写法:ws://**.We ...