Peewee Tutorial
Selected Reading
- Peewee - Discussion
- Peewee - Useful Resources
- Peewee - Quick Guide
- Peewee - Using CockroachDB
- Peewee - PostgreSQL & MySQL Extensions
- Peewee - SQLite Extensions
- Peewee - Integration with Web Frameworks
- Peewee - Query Builder
- Peewee - Database Errors
- Peewee - Atomic Transactions
- Peewee - User defined Operators
- Peewee - Retrieving Row Tuples/Dictionaries
- Peewee - SQL Functions
- Peewee - Counting & Aggregation
- Peewee - Sorting
- Peewee - Subqueries
- Peewee - Relationships & Joins
- Peewee - Connection Management
- Peewee - Defining Database Dynamically
- Peewee - Using PostgreSQL
- Peewee - Using MySQL
- Peewee - Constraints
- Peewee - Create Index
- Peewee - Delete Records
- Peewee - Update Existing Records
- Peewee - Primary & Composite Keys
- Peewee - Filters
- Peewee - Select Records
- Peewee - Insert a New Record
- Peewee - Field Class
- Peewee - Model
- Peewee - Database Class
- Peewee - Overview
- Peewee - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Peewee - Counting & Aggregation
Peewee - Counting and Aggregation
We can find number of records reported in any SELECT query by attaching count() method. For example, following statement returns number of rows in Contacts table with City=’Nasik’.
qry=Contacts.select().where (Contacts.City== Nasik ).count() print (qry)
Example
SQL has GROUP BY clause in SELECT query. Peewee supports it in the form of group_by() method. Following code returns city wise count of names in Contacts table.
from peewee import * db = SqpteDatabase( mydatabase.db ) class Contacts(BaseModel): RollNo = IntegerField() Name = TextField() City = TextField() class Meta: database = db db.create_tables([Contacts]) qry=Contacts.select(Contacts.City, fn.Count(Contacts.City).apas( count )).group_by(Contacts.City) print (qry.sql()) for q in qry: print (q.City, q.count)
The SELECT query emitted by Peewee will be as follows −
( SELECT "t1"."City", Count("t1"."City") AS "count" FROM "contacts" AS "t1" GROUP BY "t1"."City" , [])
Output
As per sample data in Contacts table, following output is displayed −
Chennai 1 Delhi 2 Indore 1 Mumbai 1 Nagpur 1 Nasik 3 Pune 1Advertisements