知乎: 使用 sqlalchemy 的 orm 方式操作数据库是一种怎样的体验?
答: 爽!
本文基于:win10 + python3.4 + sqlAlchemy 1.0.13
下面展示其操作步骤:
1. 声明基类
from sqlalchemy.ext.declarative import declarative_base Base = declarative_base()
2. 定义表
from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship class Parent(Base): __tablename__ = ‘parent‘ id = Column(Integer, primary_key=True) children = relationship("Child") def __repr__(self): return "<Parent(id=‘{}‘, children=‘{}‘)>".format(self.id, self.children) class Child(Base): __tablename__ = ‘child‘ id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey(‘parent.id‘)) def __repr__(self): return "<Child(id=‘{}‘, parent_id=‘{}‘)>".format(self.id, self.parent_id)
3. 建立连接
from sqlalchemy import create_engine engine = create_engine(‘sqlite:///:memory:‘, echo=True)
4. 建立会话
from sqlalchemy.orm import Session session = Session(engine)
5. 生成表
Base.metadata.drop_all(engine) Base.metadata.create_all(engine) # 生产环境只需运行一次!!!!
6. 添加记录
session.add_all([Parent(children=[Child() for j in range(5)]) for i in range(2)]) session.commit()
7. 查询
# 懒加载 (lazyload) # load everything, no eager loading. for parent in session.query(Parent): print(parent.children) # 联合加载 (joinedload) # load everything, joined eager loading. for parent in session.query(Parent).options(joinedload("children")): parent.children # 子查询加载 (subqueryload) # load everything, subquery eager loading. for parent in session.query(Parent).options(subqueryload("children")): parent.children
8. 完整代码
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy import create_engine from sqlalchemy.orm import Session from sqlalchemy.orm import joinedload, subqueryload # 声明基类 Base = declarative_base() # 定义表 class Parent(Base): __tablename__ = ‘parent‘ id = Column(Integer, primary_key=True) children = relationship("Child") def __repr__(self): return "<Parent(id=‘{}‘, children=‘{}‘)>".format(self.id, self.children) class Child(Base): __tablename__ = ‘child‘ id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey(‘parent.id‘)) def __repr__(self): return "<Child(id=‘{}‘, parent_id=‘{}‘)>".format(self.id, self.parent_id) # 建立连接 engine = create_engine(‘sqlite:///:memory:‘, echo=True) # 建立会话 session = Session(engine) # 生成表 Base.metadata.drop_all(engine) Base.metadata.create_all(engine) # 生产环境只需运行一次!!!! # 添加记录 session.add_all([Parent(children=[Child() for j in range(5)]) for i in range(2)]) session.commit() # 查询 # lazyload # load everything, no eager loading. for parent in session.query(Parent): print(parent.children) # joinedload # load everything, joined eager loading. for parent in session.query(Parent).options(joinedload("children")): parent.children # subqueryload # load everything, subquery eager loading. for parent in session.query(Parent).options(subqueryload("children")): parent.children
时间: 2024-10-02 03:15:28