• 三十七:数据库之SQLAlchemy外建之多对多关系


    准备工作

    from sqlalchemy import create_engine, Column, Integer, String, Float, Text, ForeignKey
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker, relationship, backref

    # 数据库信息
    host = '127.0.0.1'
    port = '3306'
    database = 'db_to_sqlalchemy'
    username = 'root'
    password = '123456'

    # 数据库类型+连接数据库的插件,这里使用的pymysql
    DB_URI = f'mysql+pymysql://{username}:{password}@{host}:{port}/{database}'

    engine = create_engine(DB_URI) # 创建引擎
    Base = declarative_base(engine) # 使用declarative_base创建基类
    session = sessionmaker(engine)()

    多对多需要一张中间表来绑定关系
    1、想把需要做多对多的模型定义出来
    2、使用sqlalchemy.Table定义一个中间表,中间表一般就是包含两个模型的外建字段,并且把两个外建作为一个复合主键
    3、在需要多对多的模型中任意选一个来定义relationship,绑定三者之间的关系,在使用relationship的时候需要传入secondary=中间表

    from sqlalchemy import Table

    # 创建中间表
    article_tag = Table(
    'article_tag', # 中间表的表名
    Base.metadata,
    Column('article_id', Integer, ForeignKey('article.id'), primary_key=True), # 中间表的字段,来自外键
    Column('tag_id', Integer, ForeignKey('tag.id'), primary_key=True), # 中间表的字段,来自外键
    # 复合主键,防止数据冗余(两个都使用主键)
    )


    class Article(Base):
    __tablename__ = 'article'
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(50), nullable=False)
    tags = relationship('Tag', backref='article', secondary=article_tag) # 关联中间表

    def __repr__(self):
    return f'Article(title: {self.title})'


    class Tag(Base):
    __tablename__ = 'tag'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50), nullable=False)

    def __repr__(self):
    return f'Tag(name: {self.name})'


    Base.metadata.drop_all() # 删除所有表
    Base.metadata.create_all() # 创建表
    
    

    插入数据

    article1 = Article(title='article1')
    article2 = Article(title='article2')

    tag1 = Tag(name='tag1')
    tag2 = Tag(name='tag2')

    article1.tags.append(tag1)
    article1.tags.append(tag2)

    article2.tags.append(tag1)
    article2.tags.append(tag2)

    session.add(article1)
    session.add(article2)

    session.commit()

    查询

  • 相关阅读:
    函数进阶:闭包、装饰器、列表生成式、生成器、迭代器
    函数基础:内置函数
    Python函数基础---参数、变量
    python函数基础:嵌套函数、作用域、匿名函数、高阶函数、递归函数
    三元运算、文件操作
    Python终端如何输出彩色字体
    文件处理: read、readline、 readlines()
    16进制、编码问题
    JSON 操作与转化
    高并发和大型网站架构相关
  • 原文地址:https://www.cnblogs.com/zhongyehai/p/11816105.html
Copyright © 2020-2023  润新知