随笔 - 91  文章 - 0  评论 - 2  阅读 - 44180

sqlalchemy多对多关联

sqlalchemy_many_to_many.py

#!-*-coding:utf-8-*-
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

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')#secondary查第三张表关联关系 backref Author反查有多少本书
    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

engine=create_engine("mysql+pymysql://root:123456@192.168.0.6/shop_db?charset=utf8",echo=False)#连接数据库 echo=TRUE输出执行过程
#?charset=utf8可插入汉字
base.metadata.create_all(engine)#创建表

 

sqlalchemy_many_to_many_api.py

from day12 import sqlalchemy_many_to_mang
from sqlalchemy.orm import sessionmaker

Session_class = sessionmaker(bind=sqlalchemy_many_to_mang.engine)  # 创建与数据库的连接session class ,注意,这里返回给session的是个class,不是实例
session = Session_class()  # 生成session实例 session会话 类似cursor
'''
b1=sqlalchemy_many_to_mang.Book(name="leran python with Alex",pub_date="2017-06-25")
b2=sqlalchemy_many_to_mang.Book(name="leran zhangbility with alex",pub_date="2016-06-25")
b3=sqlalchemy_many_to_mang.Book(name="leran hook uo girls with alex",pub_date="2015-06-25")
b4=sqlalchemy_many_to_mang.Book(name="风萧萧兮易水寒",pub_date="2018-06-25")

a1=sqlalchemy_many_to_mang.Author(name="alex")
a2=sqlalchemy_many_to_mang.Author(name="jack")
a3=sqlalchemy_many_to_mang.Author(name="rain")

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

session.add_all([b4])
'''
author_obj=session.query(sqlalchemy_many_to_mang.Author).filter(sqlalchemy_many_to_mang.Author.name=="alex").first()
print(author_obj.books)#通过作者取书
book_obj=session.query(sqlalchemy_many_to_mang.Book).filter(sqlalchemy_many_to_mang.Book.id==2).first()
print(book_obj.authors)
#book_obj.authors.remove(author_obj)#给书删除作者
#session.delete(author_obj)#删除作者
session.commit()

posted on   SZ_文彬  阅读(378)  评论(2编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示