- Peewee - Home
- Peewee - Overview
- Peewee - Database Class
- Peewee - Model
- Peewee - Field Class
- Peewee - Insert a New Record
- Peewee - Select Records
- Peewee - Filters
- Peewee - Primary & Composite Keys
- Peewee - Update Existing Records
- Peewee - Delete Records
- Peewee - Create Index
- Peewee - Constraints
- Peewee - Using MySQL
- Peewee - Using PostgreSQL
- Peewee - Defining Database Dynamically
- Peewee - Connection Management
- Peewee - Relationships & Joins
- Peewee - Subqueries
- Peewee - Sorting
- Peewee - Counting & Aggregation
- Peewee - SQL Functions
- Peewee - Retrieving Row Tuples/Dictionaries
- Peewee - User defined Operators
- Peewee - Atomic Transactions
- Peewee - Database Errors
- Peewee - Query Builder
- Peewee - Integration with Web Frameworks
- Peewee - SQLite Extensions
- Peewee - PostgreSQL & MySQL Extensions
- Peewee - Using CockroachDB
Peewee Useful Resources
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