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 ...
随机推荐
- javaweb学习总结(五)——Servlet开发(一)
一.Servlet简介 Servlet是sun公司提供的一门用于开发动态web资源的技术. Sun公司在其API中提供了一个servlet接口,用户若想用发一个动态web资源(即开发一个Java程序向 ...
- 浏览器内核控制Meta标签说明文档
浏览器内核控制Meta标签说明文档 原文链接 背景介绍 由于众所周知的情况,国内的主流浏览器都是双核浏览器:基于Webkit内核用于常用网站的高速浏览.基于IE的内核用于兼容网银.旧版网站.以360的 ...
- oracle中时间处理
--查看当前日期.时间SQL> select sysdate from dual; SQL> select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') ...
- Bash 中 SHLVL 变量为 1000 的时候
SHLVL 环境变量代表 Shell 嵌套执行的深度. $ echo $SHLVL 1 $ bash $ echo $SHLVL 2 $ bash $ echo $SHLVL 3 在 Bash 里,这 ...
- iOS为真机调试增加scribble来定位野指针
尽管在ARC中,野指针出现的频率已经大大降低了,但是仍然会有野指针困扰着我们. 在模拟器调试中,我们可以开启scribble或者zombieObject来将已经释放的内存填充无意义的内容,能够将一些非 ...
- 利用Nginx实现域名转发 不修改主机头
在conf下 新建一个 文件 格式 : 域名.conf 例如:www.test.com.conf 文件里配置: server{ listen 80; server_name www.test.com ...
- jQuery源码笔记(二):定义了一些变量和函数 jQuery = function(){}
笔记(二)也分为三部分: 一. 介绍: 注释说明:v2.0.3版本.Sizzle选择器.MIT软件许可注释中的#的信息索引.查询地址(英文版)匿名函数自执行:window参数及undefined参数意 ...
- ASM,C数据类型
汇编: db 单字节 = 8bit dw 单字 = 16bit dd 双字 = 32bit C数据类型: char 字节 8bit unsigned cha ...
- MongoDB C Driver使用教程
MongoDB C Driver使用教程 转载请注明出处http://www.cnblogs.com/oloroso/ 本指南提供简介 MongoDB C 驱动程序. 在 C API 的详细信息,请参 ...
- Python里*arg 和**kwargs的作用
Hi,伙计们.我发现Python新手们在理解*args和**kwargs这两个魔法变量时都有些困难.他们到底是什么?首先,我先告诉大家一个事实,完整地写*args和**kwargs是不必要的,我们可以 ...