- Peewee 教程
- Peewee - 首页
- Peewee - 概述
- Peewee - 数据库类
- Peewee - 模型
- Peewee - 字段类
- Peewee - 插入新记录
- Peewee - 选择记录
- Peewee - 过滤器
- Peewee - 主键和复合键
- Peewee - 更新现有记录
- Peewee - 删除记录
- Peewee - 创建索引
- Peewee - 约束
- Peewee - 使用 MySQL
- Peewee - 使用 PostgreSQL
- Peewee - 动态定义数据库
- Peewee - 连接管理
- Peewee - 关系和连接
- Peewee - 子查询
- Peewee - 排序
- Peewee - 计数和聚合
- Peewee - SQL 函数
- Peewee - 检索行元组/字典
- Peewee - 用户定义运算符
- Peewee - 原子事务
- Peewee - 数据库错误
- Peewee - 查询构建器
- Peewee - 与 Web 框架集成
- Peewee - SQLite 扩展
- Peewee - PostgreSQL 和 MySQL 扩展
- Peewee - 使用 CockroachDB
- Peewee 有用资源
- Peewee - 快速指南
- Peewee - 有用资源
- Peewee - 讨论
Peewee - 关系和连接
Peewee 支持实现不同类型的 SQL JOIN 查询。它的 Model 类有一个 join() 方法,该方法返回一个 Join 实例。
M1.joint(m2, join_type, on)
joins 表将 M1 模型映射到 m2 模型,并返回 Join 类实例。on 参数默认为 None,是作为连接谓词使用的表达式。
连接类型
Peewee 支持以下连接类型(默认值为 INNER)。
JOIN.INNER
JOIN.LEFT_OUTER
JOIN.RIGHT_OUTER
JOIN.FULL
JOIN.FULL_OUTER
JOIN.CROSS
为了展示 join() 方法的使用,我们首先声明以下模型:
db = SqliteDatabase('mydatabase.db')
class BaseModel(Model):
class Meta:
database = db
class Item(BaseModel):
itemname = TextField()
price = IntegerField()
class Brand(BaseModel):
brandname = TextField()
item = ForeignKeyField(Item, backref='brands')
class Bill(BaseModel):
item = ForeignKeyField(Item, backref='bills')
brand = ForeignKeyField(Brand, backref='bills')
qty = DecimalField()
db.create_tables([Item, Brand, Bill])
表
接下来,我们使用以下测试数据填充这些表:
项目表
项目表如下所示:
品牌表
以下是品牌表:
账单表
账单表如下所示:
要执行 Brand 和 Item 表之间的简单连接操作,请执行以下代码:
qs=Brand.select().join(Item)
for q in qs:
print ("Brand ID:{} Item Name: {} Price: {}".format(q.id, q.brandname, q.item.price))
最终输出将如下所示:
Brand ID:1 Item Name: Dell Price: 25000 Brand ID:2 Item Name: Epson Price: 12000 Brand ID:3 Item Name: HP Price: 25000 Brand ID:4 Item Name: iBall Price: 4000 Brand ID:5 Item Name: Sharp Price: 12000
连接多个表
我们有一个 Bill 模型,它与 item 和 brand 模型具有两个外键关系。要从所有三个表中提取数据,请使用以下代码:
qs=Bill.select().join(Brand).join(Item)
for q in qs:
print ("BillNo:{} Brand:{} Item:{} price:{} Quantity:{}".format(q.id, \
q.brand.brandname, q.item.itemname, q.item.price, q.qty))
根据我们的测试数据,将显示以下输出:
BillNo:1 Brand:HP Item:Laptop price:25000 Quantity:5 BillNo:2 Brand:Epson Item:Printer price:12000 Quantity:2 BillNo:3 Brand:iBall Item:Router price:4000 Quantity:5
广告