Peewee - Retrieving Row Tuples/Dictionaries



It is possible to iterate over the resultset without creating model instances. This may be achieved by using the following −

  • tuples() method.

  • dicts() method.

Example - Getting Data as Tuples

To return data of fields in SELECT query as collection of tuples, use tuples() method.

main.py

from peewee import *

db = SqliteDatabase('mydatabase.db')

class BaseModel(Model):
   class Meta:
      database = db
	  
class Contacts(BaseModel):
   RollNo = IntegerField()
   Name = TextField()
   City = TextField()
   class Meta:
      database = db
	  
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)

db.close()

Output

The output is given below −

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

Example - Getting Data as Dictionary Objects

To obtain collection of dictionary objects −

main.py

from peewee import *

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')
   
qs=Brand.select().join(Item).dicts()
lst=[]
for q in qs:
   lst.append(q)
print (lst)

db.close()

Output

The output is stated below −

[
   {'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}
]
Advertisements