Skip to main content

5 posts tagged with "SQLAlchemy"

View All Tags

Learning SQLAlchemy From Scratch

· 3 min read
Kimi Gao
Fullstack & AI

SQLAlchemy 是 Python 下著名的 ORM (Object Relational Mapping,对象关系映射)工具集,首次发布于 2006 年 2 月,并迅速在 Python 社区中广泛使用,其提供了完整的企业级持久模式,能够与 FastAPI 中的数据模型进行良好的融合,并具有高效的数据库访问特点。

图:SQLAlchemy Overview

简而言之是将类和对象转成 SQL,然后使用数据 API 执行 SQL 并获取执行结果。它的核心思想在于将关系数据库表中的记录映射成对象,以对象的形式展现,开发者可以把对数据库的操作转化为对对象的操作。

SQLAlchemy CRUD

· 5 min read
Kimi Gao
Fullstack & AI
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, ForeignKey, String, DateTime
from sqlalchemy.orm import relationship

engine = create_engine( # 创建数据库连接引擎
"sqlite:///./sql_app.db",
connect_args={"check_same_thread": False}
)
LocalSession = sessionmaker(autocommit=False, bind=engine) # 创建本地会话

Base = declarative_base() # 定义数据模型基类


class User(Base): # 定义数据模型,用户
__tablename__ = 'user' # 数据库中的表名
id = Column(Integer, primary_key=True) # id列,主键
name = Column('name', String(50)) # 定义字段name,字符串型,对应数据库中的name列
phone = Column('phone', String(50)) # 定义字段phone,字符串型,对应数据库中的phone列
bookrecords = relationship('BookRecord', backref='user') # 图书列表字段

class BookRecord(Base): # 定义数据模型,图书
__tablename__ = 'book_record' # 数据库中的表名
id = Column(Integer, primary_key=True) # id列,主键
book_name = Column('book_name', String(50)) # 书名
borrow_time = Column('borrow_time', DateTime) # 借书时间
user_id = Column(Integer, ForeignKey('user.id')) # user_id ,外键

Base.metadata.create_all(bind=engine) # 在数据库中创建表结构

... # CRUD functions

if __name__ == '__main__':
session = LocalSession() # 创建会话实例
create(session)
retrieve(session)
update(session)
delete(session)

SQLAlchemy Declare Models

· 4 min read
Kimi Gao
Fullstack & AI

在 SQLAlchemy 中定义数据模型(表结构)时,先要使用 declarative_base 类创建数据模型的基类。在继承类中,定义数据库表与 Python 对象的映射关系。

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

engine = create_engine( # 创建数据库连接引擎
"sqlite:///./sql_app.db",
connect_args={"check_same_thread": False}
)
session = sessionmaker(autocommit=False, bind=engine) # 创建本地会话
Base = declarative_base() # 创建模型基类

class User(Base): # 定义数据模型类
__tablename__ = 'user' # 数据库中对应的表名
id = Column('id', Integer, primary_key=True) # 定义字段id,整型,对应数据库的id列
name = Column('name', String(50)) # 定义字段name,字符串型,对应数据库中的name列

Base.metadata.create_all(bind=engine) # 在数据库中创建表结构

SQLAlchemy Migration Notes

· One min read
Kimi Gao
Fullstack & AI

Users coming from older versions of SQLAlchemy, especially those transitioning from the 1.x style of working, will want to review this documentation.

SQLAlchemy Relationship Configuration

· 5 min read
Kimi Gao
Fullstack & AI

在 SQLAlchemy 中使用 relationship 函数定义关联关系(表关系),常用参数如下:

  • argument: 设置另外一个用于建立关联关系的数据模型类名称,字符串型,设置时可以省略 argument 参数名,直接在第一个参数位置指定数据模型类名称。
  • uselist: 是否建立一对多关系,默认 True,若设为 False 即为一对一关系。
  • backref: 反向引用,通过指定另外一个数据模型类的关联字段名,在一对多或多对多之间建立双向关系。
  • secondary: 用于指向多对多的中间表。
  • remote_side: 当外键是数据模型类自身时使用。
  • back_populates: 当属性为反向关系时,指定另外一个数据模型类对应的关联字段名。
  • cascade: 指定级联操作时的可用动作,比如,当删除主数据时,与其关联的子表是否会同步删除对应数据。