现在来设计一个能描述“图书”与“作者”的关系的表结构,需求是

  1. 一本书可以有好几个作者一起出版
  2. 一个作者可以写好几本书
 #!/usr/bin/env python
from sqlalchemy import Table,Column,Integer,String,DATE,ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker engine = create_engine("mysql+pymysql://root:root@localhost/testuser?charset=utf8",encoding="utf-8",echo=True)
# 生成orm基类
Base = declarative_base() # 创建表映射
book_m2m_author = Table("book_m2m_author",Base.metadata,
Column("book_id",Integer,ForeignKey("books.id")),
Column("author_id",Integer,ForeignKey("authors.id"))) class Book(Base):
__tablename__ = "books"
id = Column(Integer,primary_key=True)
name = Column(String(64))
pub_date = Column(DATE)
authors = relationship("Author",secondary=book_m2m_author,backref="books") def __repr__(self):
return self.name class Author(Base):
__tablename__ = "authors"
id = Column(Integer,primary_key=True)
name = Column(String(32)) def __repr__(self):
return self.name # 构建表结构
Base.metadata.create_all(engine)
#!/usr/bin/env python
from day12 import orm_m2m_fk
from sqlalchemy.orm import sessionmaker # 创建与数据库会话实例。
session_class = sessionmaker(bind=orm_m2m_fk.engine) # 生成session实例
session = session_class() # b1 = orm_m2m_fk.Book(name="Java从入门到精通",pub_date="2018-08-08")
# b2 = orm_m2m_fk.Book(name="Python从入门到精通",pub_date="2018-08-08")
# b3 = orm_m2m_fk.Book(name="JavaScript从入门到精通",pub_date="2018-08-08")
# b4 = orm_m2m_fk.Book(name=".Net从入门到精通",pub_date="2018-08-08")
#
#
# a1 = orm_m2m_fk.Author(name="Jerry")
# a2 = orm_m2m_fk.Author(name="Tom")
# a3 = orm_m2m_fk.Author(name="Jack")
#
# b1.authors = [a1,a3]
#
# b3.authors = [a1,a2,a3]
#
# b2.authors = [a2,a3]
#
# b4.authors = [a1]
#
# session.add_all([b1,b2,b3,b4,a1,a2,a3]) a = session.query(orm_m2m_fk.Author).filter(orm_m2m_fk.Author.name=="Jerry").first()
print(a.books)
session.commit()
 C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python.exe D:/PythonStudy/charm/01/day12/orm_m2m_aip.py
2018-09-20 09:22:14,652 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2018-09-20 09:22:14,652 INFO sqlalchemy.engine.base.Engine {}
2018-09-20 09:22:14,656 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2018-09-20 09:22:14,656 INFO sqlalchemy.engine.base.Engine {}
2018-09-20 09:22:14,656 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2018-09-20 09:22:14,656 INFO sqlalchemy.engine.base.Engine {}
C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\pymysql\cursors.py:170: Warning: (1366, "Incorrect string value: '\\xD6\\xD0\\xB9\\xFA\\xB1\\xEA...' for column 'VARIABLE_VALUE' at row 484")
result = self._query(query)
2018-09-20 09:22:14,658 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2018-09-20 09:22:14,658 INFO sqlalchemy.engine.base.Engine {}
2018-09-20 09:22:14,658 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2018-09-20 09:22:14,658 INFO sqlalchemy.engine.base.Engine {}
2018-09-20 09:22:14,659 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4) COLLATE utf8mb4_bin AS anon_1
2018-09-20 09:22:14,659 INFO sqlalchemy.engine.base.Engine {}
2018-09-20 09:22:14,660 INFO sqlalchemy.engine.base.Engine DESCRIBE `book_m2m_author`
2018-09-20 09:22:14,660 INFO sqlalchemy.engine.base.Engine {}
2018-09-20 09:22:14,661 INFO sqlalchemy.engine.base.Engine DESCRIBE `books`
2018-09-20 09:22:14,661 INFO sqlalchemy.engine.base.Engine {}
2018-09-20 09:22:14,663 INFO sqlalchemy.engine.base.Engine DESCRIBE `authors`
2018-09-20 09:22:14,663 INFO sqlalchemy.engine.base.Engine {}
2018-09-20 09:22:14,668 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2018-09-20 09:22:14,668 INFO sqlalchemy.engine.base.Engine SELECT authors.id AS authors_id, authors.name AS authors_name
FROM authors
WHERE authors.name = %(name_1)s
LIMIT %(param_1)s
2018-09-20 09:22:14,669 INFO sqlalchemy.engine.base.Engine {'name_1': 'Jerry', 'param_1': 1}
2018-09-20 09:22:14,670 INFO sqlalchemy.engine.base.Engine SELECT books.id AS books_id, books.name AS books_name, books.pub_date AS books_pub_date
FROM books, book_m2m_author
WHERE %(param_1)s = book_m2m_author.author_id AND books.id = book_m2m_author.book_id
2018-09-20 09:22:14,670 INFO sqlalchemy.engine.base.Engine {'param_1': 1}
[Java从入门到精通, JavaScript从入门到精通, .Net从入门到精通]
2018-09-20 09:22:14,675 INFO sqlalchemy.engine.base.Engine COMMIT Process finished with exit code 0

pythonのsqlalchemy多对多关系的更多相关文章

  1. Python SQLAlchemy多对多外键关联时表结构

    # 创建多对多表结构 from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine import cre ...

  2. sqlalchemy 多对多关系

    # -*- coding: utf-8 -*- from sqlalchemy import Column, String, create_engine,ForeignKey,Text,Integer ...

  3. 用SQLAlchemy创建一对多,多对多关系表

    多对多关系表的创建: 如果建立好多对多关系后,我们就可以通过关系名进行循环查找,比如laowang = Teacher.query.filter(Teacher.name=='laowang').fi ...

  4. python3 + flask + sqlalchemy +orm(3):多对多关系

    一篇文章有多个tag,一个tag也可以属于多篇文章,文章和tag存在多对多关系 config.py DEBUG = True #dialect+driver://root:1q2w3e4r5t@127 ...

  5. python测试开发django-32.admin后台多对多关系ManyToManyField

    前言 一本书可以有多个作者,一个作者也可以写多本书,这种关系就是本篇要说的多对多关系. 这种场景在django里面数据库设计时候,需要用到ManyToManyField方法 多对多表设计 auther ...

  6. [ SQLAlchemy ] 自我引用型的多对多关系(Self-Referential Many-to-Many Relationship)理解

    参考: https://www.jianshu.com/p/2c6c76f94b88 https://madmalls.com/blog/post/followers-and-followeds/ 实 ...

  7. python 外键用法 多对多关系 ORM操作 模板相关

    一.app/models中写类(设计表结构) 1.普通类 class  A(models.Model): id=modles.AutoField(primary_key=True) name=mode ...

  8. Linux下开发python django程序(django数据库多对多关系)

    1.多对多关系数据访问 models.py设置 from django.db import models # Create your models here. sex_choices=( ('f',' ...

  9. python使用ORM之如何调用多对多关系

    在models.py中,我创建了两张表,他们分别是作者表和书籍表,且之间的关系是多对多. # 书 class Book(models.Model): id = models.AutoField(pri ...

随机推荐

  1. day21(1)---python的内存管理

    垃圾回收机制: 不能被程序访问到的数据,就称之为垃圾. 引用计数:引用计数是用来记录值的内存地址被记录的次数的 每一次对值地址的引用都可以使得该值的引用计数+1 每一次对值地址的释放都可以使得该值的引 ...

  2. P1273 有线电视网

    题目描述 某收费有线电视网计划转播一场重要的足球比赛.他们的转播网和用户终端构成一棵树状结构,这棵树的根结点位于足球比赛的现场,树叶为各个用户终端,其他中转站为该树的内部节点. 从转播站到转播站以及从 ...

  3. UI Automator 常用 API 整理

    主要类: import android.support.test.uiautomator.UiDevice; 作用:设备封装类,测试过程中获取设备信息和设备交互. import android.sup ...

  4. Java HttpURLConnection发送post请求示例

    public static Map<String, Object> invokeCapp(String urlStr, Map<String, Object> params) ...

  5. 故障公告:docker swarm集群“群龙无首”造成部分站点无法访问

    今天傍晚 17:38-18:18 左右,由于 docker swarm 集群出现 "The swarm does not have a leader" 问题,造成博问.闪存.园子. ...

  6. Java 向MySql 插入日期和时间正确的姿势

    Mysql和Java之间时间对应关系表: date              java.sql.Date Datetime        java.sql.Timestamp Timestamp    ...

  7. UC和QQ两个主流浏览器 * 点击触发微信分享到朋友圈或发送给朋友的功能(转载)

    转载(声明:仅供学习使用) /** * 此插件主要作用是在UC和QQ两个主流浏览器 * 上面触发微信分享到朋友圈或发送给朋友的功能 * 代码编写过程中 参考: * http://mjs.sinaimg ...

  8. Android艺术——探究Handler运行机制

    我们从开发的角度来说,Handler是Android 的消息机制的上层接口.说到Handler,大家都会说:哦,Handler这个我知道干什么的,更新UI.没错,Handler的确是用于更新UI的,具 ...

  9. 关于CentOS7.2 控制面板不显示输入法,或者无法调出输入的问题。(已解决)

    问题描述: CentOS7.2 桌面系统控制面板突然就不显示输入法的图标,快捷键也调不出输入法. 解决方法: test@base0200: ~ $ ibus-setup 调出ibus首选项--> ...

  10. linux 实现centos7在线升级最新版本内核

    Kernel  (内核)是操作系统的核心,掌握所有硬件设备的控制权,也就是说,你所希望计算机帮你完成的各项工作,都需要通过内核的帮助才能完成,当然,如果我们想完成的某个功能是内核没有的,则内核不会操控 ...