首页 > 数据库 >【Python/数据库】SQLAlchemy一对多,多对多操作

【Python/数据库】SQLAlchemy一对多,多对多操作

时间:2023-12-05 14:11:21浏览次数:47  
标签:engine SQLAlchemy name Python 数据库 db session import id

SQLAlchemy一对多操作

1. 创建多表

# create_table_ForeginKey.py

from sqlalchemy.ext.declarative import declarative_base
from salalchemy import Column, INT, VARCHAR, ForeignKey
from sqlalchemy import create_engine

Base = declarative_base()

class Student(Base):
  __tablename__ = 'student'
  id = Column(INT, primary_key=True)
  name = Column(VARCHAR(32))
  school_id = Column(INT, ForeignKey('school.id'))
  
class School(Base):
  __tablename__ = 'school'
  id = Column(INT, primary_key=True)
  name = Column(VARCHAR(32))
  
  
engine = create_engine('mysql+pymysql://root:root@localhost:3306/fast_demo?charset=utf8')
Base.metadata.create_all(engine)

2. 多表insert

1.原始增加数据 (笨)

# crud_insert_ForeignKey.py

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine

Session = sessionmaker(engine)
db_session = Session()

sch_obj = School(name='pekingUniversity')
db_session.add(sch_obj)
db_session.commit()
db_session.close()

sch_obj = db_session.query(School).filter(School.name == 'pekingUniversity').first()
stu_obj = Student(name='zs', school_id=sch_obj.id)

db_session.add(stu_obj)
db_session.commit()
db_session.close()

2. 增加数据(relationship 方法)(推荐)

create_table_ForeignKey.py
# create_table_ForeginKey.py

  from sqlalchemy.ext.declarative import declarative_base
  from salalchemy import Column, INT, VARCHAR, ForeignKey
  from sqlalchemy import create_engine
+ from sqlalchemy.orm import relationship

  Base = declarative_base()

  Class Student(Base):
    __table__ = 'student'
    id = Column(INT, primary_key=True)
    name = Column(VARCHAR(32))
    school_id = Column(INT, ForeignKey('school.id', ondelete='SET NULL'))
+   stu2sch = relationship('School',backref='sch2stu')

  Class School(Base):
    __table__ = 'school'
    id = Column(INT, primary_key=True)
    name = Column(VARCHAR(32))


  engine = create_engine('mysql+pymysql://root:root@localhost:3306/fast_demo?charset=utf8')
  Base.metadata.create_all(engine)
1. 正向
# crud_insert_ForeignKey.py

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine, School, Student

Session = sessionmaker(engine)
db_session = Session()

stu_obj = Student(name='zs', stu2sch=School(name='pekingUnivesity'))

db_session.add(stu_obj)
db_session.commit()
db_session.close()
2. 反向
# crud_insert_ForeignKey.py

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine, School, Student

Session = sessionmaker(engine)
db_session = Session()

sch_obj = School(name='Tsu')
sch_obj.sch2stu = [Student(name='zhangsan'),Student(name='lisi')]

db_session.add(sch_obj)
db_session.commit()
db_session.close()

3. 多表select

1. 原始查询数据(笨)

# crud_select_ForeignKey.py

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine,

Session = sessionmaker(engine)
db_session = Session()

# 查询
sch_obj = db_session.query(School).filter(School.name == 'pekingUniversity').first()
beijing_stu_obj = db_session.query(Student).filter(Student.school.id == sch_obj,id).first()
print(beijing_stu_obj.name,sch_obj.name)

2. 查询数据(relationship方法)(推荐)

create_table_ForeginKey.py

# create_table_ForeginKey.py

  from sqlalchemy.ext.declarative import declarative_base
  from salalchemy import Column, INT, VARCHAR, ForeignKey
  from sqlalchemy import create_engine
+ from sqlalchemy.orm import relationship

  Base = declarative_base()

  Class Student(Base):
    __table__ = 'student'
    id = Column(INT, primary_key=True)
    name = Column(VARCHAR(32))
    school_id = Column(INT, ForeignKey('school.id', ondelete='SET NULL'))
+   stu2sch = relationship('School',backref='sch2stu')

  Class School(Base):
    __table__ = 'school'
    id = Column(INT, primary_key=True)
    name = Column(VARCHAR(32))


  engine = create_engine('mysql+pymysql://root:root@localhost:3306/fast_demo?charset=utf8')
  Base.metadata.create_all(engine)
1. 正向
# crud_select_ForeignKey.py

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine,

Session = sessionmaker(engine)
db_session = Session()

# 查询
stu_obj = db_session.query(Student).filter(Student.name=='Tsu').first()
print(stu_obj.name, stu_obj.stu2sch.name)

2. 反向
# crud_select_ForeignKey.py

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine,

Session = sessionmaker(engine)
db_session = Session()

# 查询
sch_obj_list = db_session.query(School).all()
for sch in sch_obj_list:
  for stu in row.sch2stu:
    print(sch.name, stu.name)

4.多表update

# crud_update_ForeignKey.py

from my_ForeignKey import Student, ClassTable,engine

from sqlalchemy.orm import sessionmaker
DB_session = sessionmaker(engine)
db_session = DB_session()

# 更新
class_info = db_session.query(ClassTable).filter(ClassTable.name=="OldBoyS1").first()

db_session.query(Student).filter(Student.class_id == class_info.id).update({"name":"NBDragon"})

db_session.commit()
db_session.close()

5. 多表delete

  1. RESTRICT:若子表中有父表对应的关联数据,删除父表对应数据,会阻止删除。默认项
  2. NO ACTION:在MySQL中,同RESTRICT
  3. CASCADE:级联删除。
  4. SET NULL:父表对应数据被删除,子表对应数据项会设置为NULL
# crud_delete_ForeignKey.py

from my_ForeignKey import Student, ClassTable,engine

from sqlalchemy.orm import sessionmaker
DB_session = sessionmaker(engine)
db_session = DB_session()

# 删除
class_info = db_session.query(ClassTable).filter(ClassTable.name=="OldBoyS1").first()
db_session.query(Student).filter(Student.class_id == class_info.id).delete()

db_session.commit() 
db_session.close()

SQLAlchemy多对多操作

1. 创建表及关系

# create_m2m.py

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

from sqlalchemy import Column,Integer,String,ForeignKey
from sqlalchemy.orm import relationship

class Hotel(Base):
 __tablename__="hotel"
 id=Column(Integer,primary_key=True)
 girl_id = Column(Integer,ForeignKey("girl.id"))
 boy_id = Column(Integer,ForeignKey("boy.id"))

class Girl(Base):
 __tablename__="girl"
 id=Column(Integer,primary_key=True)
 name = Column(String(32),index=True)

 #创建关系
 boys = relationship("Boy",secondary="hotel",backref="girl2boy")


class Boy(Base):
 __tablename__="boy"
 id=Column(Integer,primary_key=True)
 name = Column(String(32),index=True)


from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:[email protected]:3306/dragon?charset=utf8")

Base.metadata.create_all(engine)

2. 基于relationship增加数据

# crud_insert_m2m.py

from my_M2M import Girl,Boy,Hotel,engine
 
# 创建连接
from sqlalchemy.orm import sessionmaker
# 创建数据表操作对象 sessionmaker
DB_session = sessionmaker(engine)
db_session = DB_session()

# 1.通过Boy添加Girl和Hotel数据
boy = Boy(name="DragonFire")
boy.girl2boy = [Girl(name="赵丽颖"),Girl(name="Angelababy")]
db_session.add(boy)
db_session.commit()

# 2.通过Girl添加Boy和Hotel数据
girl = Girl(name="珊珊")
girl.boys = [Boy(name="Dragon")]
db_session.add(girl)
db_session.commit()

3. 基于relationship查询数据

# ocrud_select_m2m.py

from my_M2M import Girl,Boy,Hotel,engine

# 创建连接
from sqlalchemy.orm import sessionmaker
# 创建数据表操作对象 sessionmaker
DB_session = sessionmaker(engine)
db_session = DB_session()
 
# 1.通过Boy查询约会过的所有Girl
hotel = db_session.query(Boy).all()
for row in hotel:
  for row2 in row.girl2boy:
    print(row.name,row2.name)

# 2.通过Girl查询约会过的所有Boy
hotel = db_session.query(Girl).all()
for row in hotel:
 for row2 in row.boys:
  print(row.name,row2.name)

标签:engine,SQLAlchemy,name,Python,数据库,db,session,import,id
From: https://www.cnblogs.com/Fanwenming1/p/17877086.html

相关文章

  • python练习
    1将数字汉字符号一起打印2大小写转换首字母大写3使用数学函数4注释5对字符串求长度6通过索引获取单个字符7布尔类型8空值类型9查找所属类型type10列表将数字汉字符号一起打印name="璃月"date="12月5号"message=f'{name}您好,今天是:{date}'print(message)或者可以......
  • 使用Python发送HTTP请求的最佳实践:让你的代码锐利如刀!
    在当今的数字化时代,使用Python发送HTTP请求已经成为了许多开发人员的日常任务。无论是进行API交互、网页爬取,还是构建网络服务,掌握Python的HTTP请求技巧都至关重要。但是,要想在竞争激烈的编程领域中脱颖而出,你需要掌握一些最佳实践,让你的代码锐利如刀!安装必要的库首先,确保你已经安......
  • python文件不显示cmd黑窗口,打包py,pyw文件为exe文件
    问题描述:编写的python文件为定时任务,需要长时间运行,但是打开的cmd黑色窗口看起来很不舒服,于是打包为exe文件,隐藏cmd黑色窗口步骤:1.使用pipinstallpyinstaller命令安装pyinstaller(前提是已安装python);2.很多时候出现pip版本过老的报错,此时使用pip--version查看pip版本,确定......
  • 修改python打包后的窗体图标、任务栏图标、exe图标
    前言我python开发的GUI界面(图形用户界面)一直是tkinter,打包exe一直是Pyinstaller。但是打包出来的exe图标、状态栏图标、窗体左上角图标一直是默认的羽毛,我想自定义。效果最后使用base64创建临时ico解决了该问题步骤创建icoToBase64.py,内容如下:importbase64#ico......
  • 奇迹Mu 删除MD5加密数据库语句!
    很多GM在自己都不知道的情况下,就给游戏加了MD5的加密,MD5加密通常都是32位的加密,在写程序的逻辑上,通常会进行好几次的循环加密,导致很多用户注册或是登陆的时候会显示错误,今天MU-GM给大家提供一个清除数据库MD5的SQL语句。ifexists(select*fromdbo.sysobjectswhereid=obje......
  • 使用mysqlbinlog恢复数据库(逆向或正向都可以)
    我确实喜欢写一些不一样的东西。如果我们在网上搜索“mysql恢复数据库”、“使用mysqlbinlog恢复数据库”、“mysql使用binlog恢复被删除的表”等,一般可以搜索到很多,但是仔细分析会发现,这许多的基本都在讲几件事:1、查看是否已开启在线日志,如果没有开启就开启2、查看日志文件位置3......
  • Laravel开发中的数据库迁移Database Migrations和 对象关系映射Eloquent ORM
    当涉及到Laravel中的数据库操作时,数据库迁移和EloquentORM是两个重要的概念。它们用于管理数据库结构和进行数据操作,但在功能和用途上有所不同。数据库迁移(DatabaseMigrations)是Laravel中用于管理数据库结构变化的工具。它允许您通过编写简单的代码来创建、修改或删除数......
  • Python编程:从入门到实践--Chapter16
    在16章的json数据测试如下代码时报错:[Errno22]Invalidargument:'eq_data\readable_eq_data.json'#将数据作为字符串读取并转换为python对象path=Path('eq_data\eq_data_1_day_m1.json')contents=path.read_text()all_eq_data=json.loads(contents)#将数据文件转换为......
  • 深入探讨 Python 中的装饰器和上下文管理器
    Python作为一门灵活而强大的语言,提供了许多高级特性,其中装饰器(Decorators)和上下文管理器(ContextManagers)是其中两个非常有用的概念。这两个功能性特性提供了对代码结构和行为进行修改和控制的强大工具。它们允许程序员在不修改源代码的情况下,添加、修改或扩展函数或类的功能,帮助......
  • python包迁移
    在没有网络的python环境中安装python包(从另一个环境打包转移到另一个环境)1、在有网络的电脑上安装我们需要的包2、在有网络的电脑下执行下面语句pipfreeze>requirements.txt这个时候就会在命令行所在的目录生成一个requirements.txt,这里面列出了有网络电脑的包的名字和版本。......