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 ...
随机推荐
- kettle参数、变量详细讲解[转]
kettle 3.2 以前的版本里只有 variable 和 argument,kettle 3.2 中,又引入了 parameter 概念:variable 即environment variabl ...
- [Java] Java执行Shell命令
Methods ProcessBuilder.start() 和 Runtime.exec() 方法都被用来创建一个操作系统进程(执行命令行操作),并返回 Process 子类的一个实例,该实例可用来 ...
- [Machine Learning] 机器学习常见算法分类汇总
声明:本篇博文根据http://www.ctocio.com/hotnews/15919.html整理,原作者张萌,尊重原创. 机器学习无疑是当前数据分析领域的一个热点内容.很多人在平时的工作中都或多 ...
- iptables4张表5条链
4张表:filter nat mangle raw filter:协议过滤: nat:地址转换,端口映射等: mangle:协议修改 TTL等: raw:This table is used m ...
- jquery_DOM笔记
回头补充知识: jquery事件复习: bind() 用于绑定多个事件,当某一个节点需要进行多项处理的时候使用 .使用方式 $(select).bind({event:function(),event ...
- eclipse 快捷键
Eclipse快捷键大全 Ctrl+1 快速修复(最经典的快捷键,就不用多说了) Ctrl+D: 删除当前行 Ctrl+Alt+↓ 复制当前行到下一行(复制增加) Ctrl+Alt+↑ 复制当前行到 ...
- ABAP 传入数据到EXCEL自编函数
DATA: excel TYPE ole2_object, workbook TYPE ole2_object, sheet TYPE ole2_object, ...
- jqueyr eq get用法
相信大部份人都会把这2个的用法搞错.仔细查看下API文档就可以知道.eq返回的是一个jquery对象,get返回的是一个html 对象数组.举个例子: <p style="color: ...
- css中一些常用技巧
// css中引入字体文件 @font-face { font-family: msyh; /*这里是说明调用来的字体名字*/ src: url('../font/wryh.ttf'); /*这里是字 ...
- LeetCode 26 Remove Duplicates from Sorted Array
Problem: Given a sorted array, remove the duplicates in place such that each element appear only onc ...