sqlalchemy操作----多表关联

有二张表,一张作者表,一张书表,一个作者写多本书,一本书可以由多个作者写,与是通过新加一张关系表把他们联系起来

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author aliex-hrg

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://hrg:[email protected]:3306/test?charset=utf8")
Base = declarative_base()  #生成orm基类

Base = declarative_base()
book_to_author = Table(‘book_to_author‘, Base.metadata,
                        Column(‘book_id‘,Integer,ForeignKey(‘books.id‘)),
                        Column(‘author_id‘,Integer,ForeignKey(‘authors.id‘)),
                        )

class Author(Base):
    __tablename__ = ‘authors‘ #表名
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    def __repr__(self):
        return self.name

class Book(Base):
    __tablename__ = ‘books‘ #表名
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    authors = relationship(‘Author‘, secondary=book_to_author, backref=‘books‘)
    def __repr__(self):
        return self.name

Base.metadata.create_all(engine)  #创建表

a1 = Author(name=‘alex‘)
a2 = Author(name=‘keke‘)
a3 = Author(name=‘tom‘)
b1 = Book(name=‘linux‘)
b2 = Book(name=‘python‘)
b3 = Book(name=‘C++‘)

b1.authors = [a1,a2,a3]
b2.authors = [a1,a3]
b3.authors = [a3]

Session_class = sessionmaker(bind=engine)
Session = Session_class()

Session.add_all([a1,a2,a3,b1,b2,b3])
Session.commit()
print(‘--------通过书表查关联的作者---------‘)
book_obj = Session.query(Book).filter(Book.name==‘linux‘).first()
print(book_obj.name,book_obj.authors)
print(‘--------通过作者表查关联的书---------‘)
author_obj = Session.query(Author).filter(Author.name==‘alex‘).first()
print(author_obj.name,author_obj.books)
Session.commit()

#通过书删除作者  只会从book_to_author表中删除记录
sobj = Session.query(Author).filter(Author.name==‘alex‘).first() #找出要删除作者alex的对象名
bobj = Session.query(Book).filter(Book.name==‘linux‘).first()   #找出从linux这本书中删除
bobj.authors.remove(sobj)
Session.commit()

#直接删除作者   会从authors,book_to_author中删除
#删除作者时,会把这个作者跟所有书的关联关系数据也自动删除
author_obj =Session.query(Author).filter_by(name="tom").first()
Session.delete(author_obj)
Session.commit()

  。。。。

原文地址:https://www.cnblogs.com/alex-hrg/p/9142011.html

时间: 2024-07-29 10:23:54

sqlalchemy操作----多表关联的相关文章

sqlalchemy操作----外键关联,relationship

... #!_*_coding:utf-8_*_ #__author__:"Alex huang" import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,Integer,String,ForeignKey from sqlalchemy.orm import r

Oracle中如何实现Mysql的两表关联update操作

在看<MySQL 5.1参考手册>的时候,发现MySQL提供了一种两表关联update操作.原文如下: UPDATE items,month SET items.price=month.price WHERE items.id=month.id; 在MySQL中构造表验证了一下 mysql> select * from test; +------+--------+ | id | salary | +------+--------+ | 1 | 100 | | 2 | 200 | | 3

jQuery-easyui下的多表关联的增删改操作

项目用的是Hibernate+Jquery-easyui,介绍的是多表关联的增删改操作. 很简单:只需要在多表关联的表,如员工表中关联了部门表插入数据时不能直接通过网页提交表单插入关联的部门,需要在Controller处的new一个对象,通过对象添加数据. 增加 //Servlet下的代码 Dept dept = deptService.findByIdIfo(Integer.parseInt(req.getParameter("deptId"))); employee.setDept

oracle MERGE INTO...USING两表关联操作(效率高)

数据量小的时候可以使用子查询做两表关联操作:但数据量大的时候子查询效率太低(因为是单条比对) 比如: update person1 p1 set p1.p_name=(select p_name from person2 where p1.p_id=p2.p_id) where p1.add_date>to_date('2014-09-01','yyyy-mm-dd') 而使用MERGE INTO...USING 作两表关联操作(增.删.改)就效率非常高 MERGE INTO person1 p

mongodb操作之使用javaScript实现多表关联查询

一.数据控制 mongodb操作数据量控制,千万控制好,不要因为操作的数据量过多而导致失败. 演示一下发生此类错误的错误提示: 二.多表关联查询实现 /* 声明变量bridge,用来记录两个集合所连接的桥梁. 相当于sql语句中的Join on语句,on后边跟的条件. 有了桥梁以后,再进行关联那就是易如反掌的事情啦. 关联桥梁所存储的数据是什么样的类型就需要根据你自己的需求来进行创建了. 我这里用一个对象来作为桥梁,然后调用对象中的属性. */ var bridge = db.info.find

yii2 ActiveRecord多表关联以及多表关联搜索的实现

一个老生常谈的问题.最近通过群里的反馈,觉得很多人还是没有去理解这个问题.今天把这个问题讲明白了,看看yii2 ActiveRecord是怎么个多表关联以及如何去优化这个关联. 场景需求: 假设我们有一张用户表user和一张用户渠道表auth,两张数据表通过user.id和auth.uid进行一对一关联.现需要在user列表展示auth表的来源渠道source,且该渠道可搜索. 首先我们先通过gii生成user和auth系列相关的model和操作.此处不做详细说明,有关gii的操作可参考gii详

Yii2中多表关联查询(with、join、joinwith)

表结构 现在有客户表.订单表.图书表.作者表, 客户表Customer   (id  customer_name) 订单表Order         (id  order_name   customer_id   book_id) 图书表Book          (id  book_name    author_id) 作者表Author        (id  author_name) 模型定义 下面是这4个个模型的定义,只写出其中的关联 Customer class Customer ex

oracle多表关联更新

oracle的更新语句不通MSSQL那么简单易写,就算写出来了,但执行时可能会报 这是由于set哪里的子查询查出了多行数据值,oracle规定一对一更新数据,所以提示出错.要解决这样必须保证查出来的值一一对应. 原理 Update语句的原理是先根据where条件查到数据后,如果set中有子查询,则执行子查询把值查出来赋给更新的字段,执行更新. update dept a    set a.loc = (select b.loc from test_dept b where a.deptno =

Yii2中多表关联查询(join、joinwith) with是不执行sql的

Yii2中多表关联查询(join.joinwith) 我们用实例来说明这一部分 表结构 现在有客户表.订单表.图书表.作者表, 客户表Customer (id customer_name) 订单表Order (id order_name customer_id book_id) 图书表 (id book_name author_id) 作者表 (id author_name) 模型定义 下面是这4个个模型的定义,只写出其中的关联 Customer class Customer extends \