Peewee – Retrieving Row Tuples/Dictionaries


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

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


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)

Output

The output is given below −


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

Example

To obtain collection of dictionary objects −


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

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

”;

Leave a Reply

Your email address will not be published. Required fields are marked *