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

  1. 一本书可以有好几个作者一起出版
  2. 一个作者可以写好几本书

此时你会发现,用之前学的外键好像没办法实现上面的需求了,因为

当然你更不可以像下面这样干,因为这样就你就相当于有多条书的记录了,太low b了,改书名还得都改。。。

那怎么办呢? 此时,我们可以再搞出一张中间表,就可以了

这样就相当于通过book_m2m_author表完成了book表和author表之前的多对多关联

#-*-coding:utf-8-*-
#__author__ = "logan.xu" import sqlalchemy
from sqlalchemy import create_engine,func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy import Table, Column, Integer,String,DATE, ForeignKey
from sqlalchemy.orm import relationship engine=create_engine("mysql+pymysql://root:12345678@localhost/news",encoding='utf-8',echo=True)
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)

#-*-coding:utf-8-*-
#__author__ = "logan.xu" from orm_m2m import orm_m2m
from sqlalchemy.orm import sessionmaker Session_class=sessionmaker(bind=orm_many_fk.engine) #创建与数据库的链接
session= Session_class() #生成session实例 #cursor

/Users/drizzle/PycharmProjects/2018-12-03/venv/bin/python /Users/drizzle/PycharmProjects/2018-12-03/orm_m2m/orm_m2m.py
2019-01-08 19:35:48,687 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-01-08 19:35:48,687 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,689 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-01-08 19:35:48,689 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,691 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-01-08 19:35:48,691 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,692 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-01-08 19:35:48,692 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,694 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-01-08 19:35:48,695 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,695 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-01-08 19:35:48,695 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,696 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4)
COLLATE utf8mb4_bin AS anon_1
2019-01-08 19:35:48,696 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,697 INFO sqlalchemy.engine.base.Engine DESCRIBE `book_m2m_author`
2019-01-08 19:35:48,697 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,698 INFO sqlalchemy.engine.base.Engine ROLLBACK
2019-01-08 19:35:48,698 INFO sqlalchemy.engine.base.Engine DESCRIBE `books`
2019-01-08 19:35:48,698 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,699 INFO sqlalchemy.engine.base.Engine ROLLBACK
2019-01-08 19:35:48,699 INFO sqlalchemy.engine.base.Engine DESCRIBE `authors`
2019-01-08 19:35:48,699 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,699 INFO sqlalchemy.engine.base.Engine ROLLBACK
2019-01-08 19:35:48,700 INFO sqlalchemy.engine.base.Engine
CREATE TABLE books (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(64),
pub_date DATE,
PRIMARY KEY (id)
) 2019-01-08 19:35:48,700 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,793 INFO sqlalchemy.engine.base.Engine COMMIT
2019-01-08 19:35:48,794 INFO sqlalchemy.engine.base.Engine
CREATE TABLE authors (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(32),
PRIMARY KEY (id)
) 2019-01-08 19:35:48,794 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,800 INFO sqlalchemy.engine.base.Engine COMMIT
2019-01-08 19:35:48,802 INFO sqlalchemy.engine.base.Engine
CREATE TABLE book_m2m_author (
book_id INTEGER,
author_id INTEGER,
FOREIGN KEY(book_id) REFERENCES books (id),
FOREIGN KEY(author_id) REFERENCES authors (id)
) 2019-01-08 19:35:48,802 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:35:48,811 INFO sqlalchemy.engine.base.Engine COMMIT Process finished with exit code 0
mysql> show tables;
+-----------------+
| Tables_in_news |
+-----------------+
| address |
| authors |
| book_m2m_author |
| books |
| customer |
| student |
| study_record |
| user |
+-----------------+
8 rows in set (0.00 sec) mysql> show create table authors;
+---------+--------------------------------------------------------------+
| Table | Create Table |
+---------+--------------------------------------------------------------+
| authors | CREATE TABLE `authors` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+---------+-------------------------------------------------------------+
1 row in set (0.00 sec) mysql> show create table book_m2m_author;
+-----------------+--------------------------------------------------------------------------+
| Table | Create Table |
+-----------------+--------------------------------------------------------------------------+
| book_m2m_author | CREATE TABLE `book_m2m_author` (
`book_id` int(11) DEFAULT NULL,
`author_id` int(11) DEFAULT NULL,
KEY `book_id` (`book_id`),
KEY `author_id` (`author_id`),
CONSTRAINT `book_m2m_author_ibfk_1` FOREIGN KEY (`book_id`) REFERENCES `books` (`id`),
CONSTRAINT `book_m2m_author_ibfk_2` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-----------------+-------------------------------------------------------------------------+
1 row in set (0.00 sec) mysql> show create table books;
+-------+-------------------------------------------------------------+
| Table | Create Table |
+-------+-------------------------------------------------------------+
| books | CREATE TABLE `books` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) DEFAULT NULL,
`pub_date` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+---------------------------------------------------------------------+

mysql> desc book_m2m_author;
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| book_id | int(11) | YES | MUL | NULL | |
| author_id | int(11) | YES | MUL | NULL | |
+-----------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)


mysql> desc books;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(64) | YES | | NULL | |
| pub_date | date | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)


mysql> desc authors;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(32) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

 
#-*-coding:utf-8-*-
#__author__ = "logan.xu" from m2m import orm_m2m
from sqlalchemy.orm import sessionmaker Session_class=sessionmaker(bind=orm_m2m.engine) #创建与数据库的链接
session= Session_class() #生成session实例 #cursor #插入数据 b1= orm_m2m.Book(name="learn python with Alex", pub_date="2019-01-08")
b2= orm_m2m.Book(name="learn JAVA with Alex", pub_date="2019-01-09")
b3= orm_m2m.Book(name="learn LINUX with Alex", pub_date="2019-01-10") a1= orm_m2m.Author(name="Alex")
a2= orm_m2m.Author(name="Jack")
a3= orm_m2m.Author(name="Eric") b1.authors=[a1,a3]
b3.authors=[a1,a2,a3] session.add_all([b1,b2,b3,a1,a2,a3]) session.commit()
/Users/drizzle/PycharmProjects/2018-12-03/venv/bin/python /Users/drizzle/PycharmProjects/2018-12-03/m2m/orm_m2m_api.py
2019-01-08 19:54:48,757 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-01-08 19:54:48,757 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:54:48,759 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-01-08 19:54:48,759 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:54:48,760 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-01-08 19:54:48,761 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:54:48,761 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-01-08 19:54:48,761 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:54:48,764 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-01-08 19:54:48,764 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:54:48,765 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-01-08 19:54:48,765 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:54:48,765 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4)
COLLATE utf8mb4_bin AS anon_1
2019-01-08 19:54:48,765 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:54:48,767 INFO sqlalchemy.engine.base.Engine DESCRIBE `book_m2m_author`
2019-01-08 19:54:48,767 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:54:48,768 INFO sqlalchemy.engine.base.Engine DESCRIBE `books`
2019-01-08 19:54:48,768 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:54:48,769 INFO sqlalchemy.engine.base.Engine DESCRIBE `authors`
2019-01-08 19:54:48,769 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:54:48,777 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-01-08 19:54:48,777 INFO sqlalchemy.engine.base.Engine INSERT INTO authors (name) VALUES (%(name)s)
2019-01-08 19:54:48,777 INFO sqlalchemy.engine.base.Engine {'name': 'Alex'}
2019-01-08 19:54:48,778 INFO sqlalchemy.engine.base.Engine INSERT INTO authors (name) VALUES (%(name)s)
2019-01-08 19:54:48,778 INFO sqlalchemy.engine.base.Engine {'name': 'Jack'}
2019-01-08 19:54:48,779 INFO sqlalchemy.engine.base.Engine INSERT INTO authors (name) VALUES (%(name)s)
2019-01-08 19:54:48,779 INFO sqlalchemy.engine.base.Engine {'name': 'Eric'}
2019-01-08 19:54:48,780 INFO sqlalchemy.engine.base.Engine INSERT INTO books (name, pub_date) VALUES (%(name)s, %(pub_date)s)
2019-01-08 19:54:48,780 INFO sqlalchemy.engine.base.Engine {'name': 'learn python with Alex', 'pub_date': '2019-01-08'}
2019-01-08 19:54:48,780 INFO sqlalchemy.engine.base.Engine INSERT INTO books (name, pub_date) VALUES (%(name)s, %(pub_date)s)
2019-01-08 19:54:48,781 INFO sqlalchemy.engine.base.Engine {'name': 'learn LINUX with Alex', 'pub_date': '2019-01-10'}
2019-01-08 19:54:48,781 INFO sqlalchemy.engine.base.Engine INSERT INTO books (name, pub_date) VALUES (%(name)s, %(pub_date)s)
2019-01-08 19:54:48,781 INFO sqlalchemy.engine.base.Engine {'name': 'learn JAVA with Alex', 'pub_date': '2019-01-09'}
2019-01-08 19:54:48,782 INFO sqlalchemy.engine.base.Engine INSERT INTO book_m2m_author (book_id, author_id) VALUES (%(book_id)s, %(author_id)s)
2019-01-08 19:54:48,782 INFO sqlalchemy.engine.base.Engine ({'book_id': 2, 'author_id': 1}, {'book_id': 2, 'author_id': 2},
{'book_id': 2, 'author_id': 3}, {'book_id': 1, 'author_id': 1}, {'book_id': 1, 'author_id': 3})
2019-01-08 19:54:48,783 INFO sqlalchemy.engine.base.Engine COMMIT Process finished with exit code 0
mysql> select * from authors;
+----+------+
| id | name |
+----+------+
| 1 | Alex |
| 2 | Jack |
| 3 | Eric |
+----+------+
3 rows in set (0.00 sec) mysql> select * from book_m2m_author;
+---------+-----------+
| book_id | author_id |
+---------+-----------+
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
| 1 | 1 |
| 1 | 3 |
+---------+-----------+
5 rows in set (0.00 sec) mysql> select * from books;
+----+------------------------+------------+
| id | name | pub_date |
+----+------------------------+------------+
| 1 | learn python with Alex | 2019-01-08 |
| 2 | learn LINUX with Alex | 2019-01-10 |
| 3 | learn JAVA with Alex | 2019-01-09 |
+----+------------------------+------------+
3 rows in set (0.00 sec)
#查询
#-*-coding:utf-8-*-
#__author__ = "logan.xu" from m2m import orm_m2m
from sqlalchemy.orm import sessionmaker Session_class=sessionmaker(bind=orm_m2m.engine) #创建与数据库的链接
session= Session_class() #生成session实例 #cursor #插入数据 #b1= orm_m2m.Book(name="learn python with Alex", pub_date="2019-01-08")#
#b2= orm_m2m.Book(name="learn JAVA with Alex", pub_date="2019-01-09")
#b3= orm_m2m.Book(name="learn LINUX with Alex", pub_date="2019-01-10")
#
#a1= orm_m2m.Author(name="Alex")
#a2= orm_m2m.Author(name="Jack")
#a3= orm_m2m.Author(name="Eric")
#
#b1.authors=[a1,a3]
#b3.authors=[a1,a2,a3]
#
#session.add_all([b1,b2,b3,a1,a2,a3]) #查询数据
author_obj=session.query(orm_m2m.Author).filter(orm_m2m.Author.name=="alex").first()
print(author_obj.books) session.commit()
/Users/drizzle/PycharmProjects/2018-12-03/venv/bin/python /Users/drizzle/PycharmProjects/2018-12-03/m2m/orm_m2m_api.py
2019-01-08 19:59:34,860 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-01-08 19:59:34,860 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:59:34,862 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-01-08 19:59:34,862 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:59:34,864 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-01-08 19:59:34,864 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:59:34,865 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-01-08 19:59:34,865 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:59:34,868 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-01-08 19:59:34,868 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:59:34,869 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-01-08 19:59:34,869 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:59:34,870 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4)
COLLATE utf8mb4_bin AS anon_1
2019-01-08 19:59:34,870 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:59:34,871 INFO sqlalchemy.engine.base.Engine DESCRIBE `book_m2m_author`
2019-01-08 19:59:34,871 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:59:34,872 INFO sqlalchemy.engine.base.Engine DESCRIBE `books`
2019-01-08 19:59:34,872 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:59:34,873 INFO sqlalchemy.engine.base.Engine DESCRIBE `authors`
2019-01-08 19:59:34,873 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 19:59:34,879 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-01-08 19:59:34,880 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
2019-01-08 19:59:34,880 INFO sqlalchemy.engine.base.Engine {'name_1': 'alex', 'param_1': 1}
2019-01-08 19:59:34,882 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
2019-01-08 19:59:34,882 INFO sqlalchemy.engine.base.Engine {'param_1': 1}
[learn LINUX with Alex, learn python with Alex]
2019-01-08 19:59:34,883 INFO sqlalchemy.engine.base.Engine COMMIT Process finished with exit code 0
#-*-coding:utf-8-*-
#__author__ = "logan.xu" from m2m import orm_m2m
from sqlalchemy.orm import sessionmaker Session_class=sessionmaker(bind=orm_m2m.engine) #创建与数据库的链接
session= Session_class() #生成session实例 #cursor #插入数据 #b1= orm_m2m.Book(name="learn python with Alex", pub_date="2019-01-08")#
#b2= orm_m2m.Book(name="learn JAVA with Alex", pub_date="2019-01-09")
#b3= orm_m2m.Book(name="learn LINUX with Alex", pub_date="2019-01-10")
#
#a1= orm_m2m.Author(name="Alex")
#a2= orm_m2m.Author(name="Jack")
#a3= orm_m2m.Author(name="Eric")
#
#b1.authors=[a1,a3]
#b3.authors=[a1,a2,a3]
#
#session.add_all([b1,b2,b3,a1,a2,a3]) #查询数据
author_obj=session.query(orm_m2m.Author).filter(orm_m2m.Author.name=="alex").first()
print(author_obj.books) book_obj=session.query(orm_m2m.Book).filter(orm_m2m.Book.id==2).first()
print(book_obj) session.commit()
/Users/drizzle/PycharmProjects/2018-12-03/venv/bin/python /Users/drizzle/PycharmProjects/2018-12-03/m2m/orm_m2m_api.py
2019-01-08 20:03:36,934 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-01-08 20:03:36,934 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:03:36,936 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-01-08 20:03:36,936 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:03:36,937 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-01-08 20:03:36,937 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:03:36,938 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-01-08 20:03:36,938 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:03:36,941 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-01-08 20:03:36,941 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:03:36,942 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-01-08 20:03:36,942 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:03:36,942 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4)
COLLATE utf8mb4_bin AS anon_1
2019-01-08 20:03:36,942 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:03:36,943 INFO sqlalchemy.engine.base.Engine DESCRIBE `book_m2m_author`
2019-01-08 20:03:36,943 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:03:36,945 INFO sqlalchemy.engine.base.Engine DESCRIBE `books`
2019-01-08 20:03:36,945 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:03:36,946 INFO sqlalchemy.engine.base.Engine DESCRIBE `authors`
2019-01-08 20:03:36,946 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:03:36,953 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-01-08 20:03:36,953 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
2019-01-08 20:03:36,953 INFO sqlalchemy.engine.base.Engine {'name_1': 'alex', 'param_1': 1}
2019-01-08 20:03:36,955 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
2019-01-08 20:03:36,955 INFO sqlalchemy.engine.base.Engine {'param_1': 1}
[learn LINUX with Alex, learn python with Alex]
2019-01-08 20:03:36,957 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
WHERE books.id = %(id_1)s
LIMIT %(param_1)s
2019-01-08 20:03:36,957 INFO sqlalchemy.engine.base.Engine {'id_1': 2, 'param_1': 1}
learn LINUX with Alex
2019-01-08 20:03:36,958 INFO sqlalchemy.engine.base.Engine COMMIT Process finished with exit code 0
#-*-coding:utf-8-*-
#__author__ = "logan.xu" from m2m import orm_m2m
from sqlalchemy.orm import sessionmaker Session_class=sessionmaker(bind=orm_m2m.engine) #创建与数据库的链接
session= Session_class() #生成session实例 #cursor #插入数据 #b1= orm_m2m.Book(name="learn python with Alex", pub_date="2019-01-08")#
#b2= orm_m2m.Book(name="learn JAVA with Alex", pub_date="2019-01-09")
#b3= orm_m2m.Book(name="learn LINUX with Alex", pub_date="2019-01-10")
#
#a1= orm_m2m.Author(name="Alex")
#a2= orm_m2m.Author(name="Jack")
#a3= orm_m2m.Author(name="Eric")
#
#b1.authors=[a1,a3]
#b3.authors=[a1,a2,a3]
#
#session.add_all([b1,b2,b3,a1,a2,a3]) #查询数据
author_obj=session.query(orm_m2m.Author).filter(orm_m2m.Author.name=="alex").first()
print(author_obj.books) book_obj=session.query(orm_m2m.Book).filter(orm_m2m.Book.id==2).first()
print(book_obj.authors) session.commit()
/Users/drizzle/PycharmProjects/2018-12-03/venv/bin/python /Users/drizzle/PycharmProjects/2018-12-03/m2m/orm_m2m_api.py
2019-01-08 20:04:49,122 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-01-08 20:04:49,122 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:04:49,124 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-01-08 20:04:49,124 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:04:49,126 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-01-08 20:04:49,126 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:04:49,127 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-01-08 20:04:49,127 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:04:49,130 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-01-08 20:04:49,130 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:04:49,131 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-01-08 20:04:49,131 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:04:49,131 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4)
COLLATE utf8mb4_bin AS anon_1
2019-01-08 20:04:49,131 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:04:49,132 INFO sqlalchemy.engine.base.Engine DESCRIBE `book_m2m_author`
2019-01-08 20:04:49,132 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:04:49,133 INFO sqlalchemy.engine.base.Engine DESCRIBE `books`
2019-01-08 20:04:49,133 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:04:49,135 INFO sqlalchemy.engine.base.Engine DESCRIBE `authors`
2019-01-08 20:04:49,135 INFO sqlalchemy.engine.base.Engine {}
2019-01-08 20:04:49,141 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-01-08 20:04:49,141 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
2019-01-08 20:04:49,141 INFO sqlalchemy.engine.base.Engine {'name_1': 'alex', 'param_1': 1}
2019-01-08 20:04:49,143 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
2019-01-08 20:04:49,143 INFO sqlalchemy.engine.base.Engine {'param_1': 1}
[learn LINUX with Alex, learn python with Alex]
2019-01-08 20:04:49,145 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
WHERE books.id = %(id_1)s
LIMIT %(param_1)s
2019-01-08 20:04:49,145 INFO sqlalchemy.engine.base.Engine {'id_1': 2, 'param_1': 1}
2019-01-08 20:04:49,146 INFO sqlalchemy.engine.base.Engine SELECT authors.id AS authors_id, authors.name AS authors_name
FROM authors, book_m2m_author
WHERE %(param_1)s = book_m2m_author.book_id AND authors.id = book_m2m_author.author_id
2019-01-08 20:04:49,146 INFO sqlalchemy.engine.base.Engine {'param_1': 2}
[Alex, Jack, Eric]
2019-01-08 20:04:49,147 INFO sqlalchemy.engine.base.Engine COMMIT Process finished with exit code 0

Python3-sqlalchemy-orm 多对多关系建表、插入数据、查询数据的更多相关文章

  1. Entity Framework 6 Recipes 2nd Edition(10-9)译 -> 在多对多关系中为插入和删除使用存储过程

    10-9. 在多对多关系中为插入和删除使用存储过程 问题 想要在一个无载荷的多对多关系中使用存储过程(存储过程只影响关系的连接表) 解决方案 假设有一个多对多关系的作者( Author)表和书籍( B ...

  2. orm 语法 数据库连接、建表、增删改查、回滚、单键关联 、多键关联、三表关联

    1.数据库连接, #!usr/bin/env/python # -*- coding:utf-8 -*- # from wangteng import sqlalchemy from sqlalche ...

  3. Python sqlalchemy orm 多对多外键关联

    多对多外键关联 注:使用三张表进行对应关联 实现代码: # 创建3个表 配置外键关联 # 调用Column创建字段 加类型 from sqlalchemy import Table, Column, ...

  4. sqlalchemy操作----建表 插入 查询 删除

    ... #!_*_coding:utf-8_*_ #__author__:"Alex huang" import sqlalchemy from sqlalchemy import ...

  5. GreenDao关系建表

    关系 在greenDAO,实体涉及使用一对一或一对多的关系.例如,如果要模拟一个1:greenDAOñ关系,你将有一个一对一和一对多的关系.但是,请注意,一对一和一对多的关系不是相互连接,所以你必须同 ...

  6. mysql 常用命令,连接数据库,查看建表语句,批量导入数据,批量更新数据,连接查询

    1. 1)MySQL 连接本地数据库,从cmd中进入mysql命令编辑器: root root分别为用户名和密码 mysql -uroot -proot 2)MySQL 连接本地数据库,用户名为“ro ...

  7. sql server建库建表(数据库和数据表的常用操作)

    数据库和数据表 (开发常用 操作) 一,数据库的创建 一个SQLServer 是由两个文件组成的:数据文件(mdf) 和日志文件(ldf),所以我们创建数据库就是要为其指定数据库名.数据文件和日志文件 ...

  8. mysql 个人博客应用的建表和相关查询

    一.建表 用户表tb_user create table if not exists tb_user( user_id int auto_increment, ) not null, user_pas ...

  9. 50个SQL语句(MySQL版) 建表 插入数据

    本学期正在学习数据库,前段时间老师让我们做一下50个经典SQL语句,当时做的比较快,有一些也是百度的,自我感觉理解的不是很透彻. 所以从本篇随笔开始,我将进行50个经典SQL语句的复盘,加深理解. 答 ...

随机推荐

  1. 将base64Url对应图片保存到本地

    上图中的内容就是base64编码之后对应的Url  图中base64,之前的都是用于声明该图片的格式以及它的编码格式  base64,之后的就是该图片对应的数据了 我们只需要把数据转换为字节保存下来即 ...

  2. 基于小熊派Hi3861鸿蒙开发的IoT物联网学习【五】

    BearPi-HM_Nano开发板鸿蒙OS内核编程开发--消息队列 什么是消息队列?        答:消息队列中间件是分布式系统中重要的组件,主要解决应用耦合.异步消息.流量削锋等问题.实现高性能. ...

  3. Mac OS系统安装pymssql 报错

    Mac OS系统安装pymssql 一开始报错:缺少Cython,于是pip install Cython 然后还是报错:解决办法如下操作: 首先安装freetds 在 FreeTDS stable ...

  4. Scrapy+splash报错 Connection was refused by other side

    报错信息如下: Traceback (most recent call last):   File "/usr/local/lib/python3.7/site-packages/scrap ...

  5. Python - 浅拷贝的四种实现方式

    浅拷贝详解 https://www.cnblogs.com/poloyy/p/15084277.html 方式一:使用切片 [:] 列表 # 浅拷贝 [:] old_list = [1, 2, [3, ...

  6. Vue项目发布的问题--http://localhost:8088/static/fonts/fontawesome-webfont.af7ae50.woff2

    问题:ngnix将8080转成80对外访问,找不对woff2等文件 一\ 搭建环境 ngnix-->conf中 server { listen 80; server_name 10.9.240. ...

  7. form 表单提交的另一种方式 js

    <html> <head> <script type="text/javascript"> function formSubmit() { fm ...

  8. js学习笔记之正则

    () 是为了提取匹配的字符串.表达式中有几个()就有几个相应的匹配字符串.(\s*)表示连续空格的字符串.[]是定义匹配的字符范围.比如 [a-zA-Z0-9] 表示相应位置的字符要匹配英文字符和数字 ...

  9. Java面向对象05——创建对象内存分析

  10. CCS box-flex属性

    box-flex==按比例分配父标签的宽度or高度空间 1.非固定分配 eg.一块地总150平方分配给三孩子,按照2:1:1分 #老大 { 房子-分配: 2; } = 75平 #老二 { 房子-分配: ...