# -*- 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的更多相关文章

  1. 基于Python的SQLAlchemy的操作

    安装 在Python使用SQLAlchemy的首要前提是安装相应的模块,当然作为python的优势,可以到python安装目录下的scripts下,同时按住shift+加上鼠标左键,从而在菜单中打开命 ...

  2. SQLAlchemy(1) -- Python的SQLAlchemy和ORM

    Python的SQLAlchemy和ORM(object-relational mapping:对象关系映射) web编程中有一项常规任务就是创建一个有效的后台数据库.以前,程序员是通过写sql语句, ...

  3. python使用sqlalchemy连接pymysql数据库

    python使用sqlalchemy连接mysql数据库 字数833 阅读461 评论0 喜欢1 sqlalchemy是python当中比较出名的orm程序. 什么是orm? orm英文全称objec ...

  4. python之SQLAlchemy

    ORM介绍 orm英文全称object relational mapping,就是对象映射关系程序,简单来说我们类似python这种面向对象的程序来说一切皆对象,但是我们使用的数据库却都是关系型的,为 ...

  5. 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 ...

  6. Python’s SQLAlchemy vs Other ORMs[转发 6]SQLAlchemy

    SQLAlchemy SQLAlchemy is an open source SQL toolkit and ORM for the Python programming language rele ...

  7. 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 ...

  8. 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 ...

  9. Python’s SQLAlchemy vs Other ORMs[转发 0]

    原文地址:http://pythoncentral.io/sqlalchemy-vs-orms/ Overview of Python ORMs As a wonderful language, Py ...

  10. 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 ...

随机推荐

  1. IK分词器 整合solr4.7 含同义词、切分词、停止词

    转载请注明出处! IK分词器如果配置成 <fieldType name="text_ik" class="solr.TextField"> < ...

  2. WP8.1 RT 生命周期详解‏‏‏‏‏‏‏‏‏‏‏‏‏

                应用状态关系转换图 根据此“应用状态关系转换图”.有以下: 三个状态: NotRunning:未运行    Running:运行中   Suspended:挂起 三个事件: A ...

  3. jQuery包装集

    jQuery包装集指的是通过$()方法返回的一个元素集,这跟一般的javascript数组有所区别, 包装集在后者的基础上还有一些初始化的函数和属性. 我们可以对二者进行一个比较: jsdiv = d ...

  4. thinkphp3.2跨控制器调用其他模块的方法

    thinphp中前台后台都有互相调用方法,这样可以省去重复内容. 1 2 $hello = new \Admin\Common\Fun\hello(); $hello->hehe(); 调用其他 ...

  5. 十六天 css汇总、js汇总、dom汇总

    1.css补充之  后台管理界面  顶部导航栏.左边菜单栏.右边内容栏固定在屏幕相应位置 会有上下左右滚动条,设定窗口最小值,使页面不乱.注意overflow:auto要与position:absol ...

  6. ACM-ICPC退役选手的发言——满满的正能量(短视频)

    这是我在北京林业大学ACM-ICPC竞赛说明会上发言的录像 希望能激励大家在奋斗的道路上披荆斩棘,勇往直前!

  7. With great power comes great responsibility

    We trust you have received the usual lecture from the local SystemAdministrator. It usually boils do ...

  8. 万全R630服务器组装RAID5阵列

    随笔, 昨天领导让我给一台服务器做系统,本身作为开发的我有一些挑战.而且领导说的事,怎么着也得努努力试试不是? 下午去机房找到服务器本以为仅仅是装个系统完事,而且据我了解服务器本身有系统,以为拿着系统 ...

  9. 摇一摇js 实现

    if (window.DeviceMotionEvent) { window.addEventListener('devicemotion',deviceMotionHandler, false); ...

  10. java 项目中几种O实体类的概念

    经常会接触到vo,do,dto的概念,本文从领域建模中的实体划分和项目中的实际应用情况两个角度,对这几个概念进行简析. 得出的主要结论是:在项目应用中,vo对应于页面上需要显示的数据(表单),do对应 ...