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

  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. Python 爬取页面内容

    import urllib.request import requests from bs4 import BeautifulSoup url = "http://www.stats.gov ...

  2. Virustotal工具产品初研

    一.产品新特点 1.群体智能 2.VT图 3.VT Yara 规则的生成与优化 4.内容搜索优化(大小及提交数量) 二.产品功能 1. --->安全管理员 威胁平台资源丰富 TIP .MISP ...

  3. vue页面初始化

    HTML: <div id="app"> <input type="" class="app" v-model=" ...

  4. 探索HashMap源码 一行一行解析 jdk1.7版本

    今天我们来说一说,HashMap的源码到底是个什么? 面试大厂这方面一定会经常问到,很重要的.以jdk1.7 为标准    先带着大家过一遍 是由数组.链表组成 , 数组的优点是:每个元素有对应下标, ...

  5. 我一个五年Android开发,居然被一个技术不如我的面试官嫌弃了......

    背景 首先介绍一下自己的情况.目前所在的是一家小的创业公司,待了5年多,薪资一般吧.由于这几年公司也在转型.工作经历大概可以分为 3 个阶段. 第一阶段是从进公司开始做 android app 开发, ...

  6. 关于java新特性lambda表达式的理解即使用

    Lambda 表达式的使用 1.举例: (o1,o2) -> Integer.compare(o1,o2); 2.格式: -> : lambda操作符 或 箭头操作符 ->左边 : ...

  7. zookeeper的简介和相关命令操作

    .personSunflowerP { background: rgba(51, 153, 0, 0.66); border-bottom: 1px solid rgba(0, 102, 0, 1); ...

  8. excel的导入与导出---通用版

    excel的导入与导出---通用版 web项目关于导入导出的业务场景很常见,最近我就又遇到了这个业务场景.这次将最近半个月做的导入导出总结一下 使用的pom如下,主要还是阿里巴巴的easyexcel依 ...

  9. Install Fabric 1.8.3 Manually on Ubuntu 12.04

    When you install Fabric with apt-get install fabric, you get a fabric with version 1.3.x, which is t ...

  10. 关于解决numpy使用sklearn时的警告问题

    关于解决numpy使用sklearn时的警告问题 在使用的时候,出现提示 :219: RuntimeWarning: numpy.ufunc size changed, may indicate bi ...