Peewee - 檢索行元組/字典



無需建立模型例項即可迭代結果集。這可以透過使用以下方式實現 -

  • tuples() 方法。

  • dicts() 方法。

示例

若要以元組集合形式返回選擇查詢中的欄位資料,請使用 tuples() 方法。

qry=Contacts.select(Contacts.City, fn.Count(Contacts.City).alias('count'))
   .group_by(Contacts.City).tuples()
lst=[]
for q in qry:
   lst.append(q)
print (lst)

輸出

輸出如下所示 -

[
   ('Chennai', 1), 
   ('Delhi', 2), 
   ('Indore', 1), 
   ('Mumbai', 1), 
   ('Nagpur', 1), 
   ('Nasik', 3), 
   ('Pune', 1)
]

示例

若要獲取字典物件集合 -

qs=Brand.select().join(Item).dicts()
lst=[]
for q in qs:
   lst.append(q)
print (lst)

輸出

輸出如下所示 -

[
   {'id': 1, 'brandname': 'Dell', 'item': 1}, 
   {'id': 2, 'brandname': 'Epson', 'item': 2}, 
   {'id': 3, 'brandname': 'HP', 'item': 1}, 
   {'id': 4, 'brandname': 'iBall', 'item': 3},
   {'id': 5, 'brandname': 'Sharp', 'item': 2}
]
廣告
© . All rights reserved.