Peewee - 关系和连接
Peewee 支持实现不同类型的 SQL JOIN 查询。 它的 Model 类有一个返回 Join 实例的 join() 方法。
M1.joint(m2, join_type, on)
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])
表
接下来,我们用以下测试数据填充这些表 −
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 模型,它与商品和品牌模型有两个外键关系。 要从所有三个表中获取数据,请使用以下代码 −
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

