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 - Subqueries
Peewee - Subqueries
In SQL, a subquery is an embedded query in WHERE clause of another query. We can implement subquery as a model.select() as a parameter inside where attribute of outer model.select() statement.
To demonstrate use of subquery in Peewee, let us use defined following models −
from peewee import * db = SqpteDatabase( mydatabase.db ) class BaseModel(Model): class Meta: database = db class Contacts(BaseModel): RollNo = IntegerField() Name = TextField() City = TextField() class Branches(BaseModel): RollNo = IntegerField() Faculty = TextField() db.create_tables([Contacts, Branches])
After tables are created, they are populated with following sample data −
Contacts table
The contacts table is given below −
In order to display name and city from contact table only for RollNo registered for ETC faculty, following code generates a SELECT query with another SELECT query in its WHERE clause.
#this query is used as subquery faculty=Branches.select(Branches.RollNo).where(Branches.Faculty=="ETC") names=Contacts.select().where (Contacts.RollNo .in_(faculty)) print ("RollNo and City for Faculty= ETC ") for name in names: print ("RollNo:{} City:{}".format(name.RollNo, name.City)) db.close()
Above code will display the following result:
RollNo and City for Faculty= ETC RollNo:103 City:Indore RollNo:104 City:Nasik RollNo:108 City:Delhi RollNo:110 City:NasikAdvertisements