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_OUTER

  • 加入交叉

为了展示 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])

Tables


接下来,我们用以下测试数据填充这些表:

项目表

项目表如下:

Item Table

品牌表

以下是品牌表:

Brand Table

账单表

账单表如下:

Bill Table

要在 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