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 - User defined Operators
Peewee - User defined Operators
Peewee has Expression class with the help of which we can add any customized operator in Peewee’s pst of operators. Constructor for Expression requires three arguments, left operand, operator and right operand.
op=Expression(left, operator, right)
Using Expression class, we define a mod() function that accepts arguments for left and right and ‘%’ as operator.
from peewee import Expression # the building block for expressions def mod(lhs, rhs): return Expression(lhs, % , rhs)
Example
We can use it in a SELECT query to obtain pst of records in Contacts table with even id.
from peewee import * db = SqpteDatabase( mydatabase.db ) class BaseModel(Model): class Meta: database = db class Contacts(BaseModel): RollNo = IntegerField() Name = TextField() City = TextField() db.create_tables([Contacts]) from peewee import Expression # the building block for expressions def mod(lhs, rhs): return Expression(lhs, % , rhs) qry=Contacts.select().where (mod(Contacts.id,2)==0) print (qry.sql()) for q in qry: print (q.id, q.Name, q.City)
This code will emit following SQL query represented by the string −
( SELECT "t1"."id", "t1"."RollNo", "t1"."Name", "t1"."City" FROM "contacts" AS "t1" WHERE (("t1"."id" % ?) = ?) , [2, 0])
Output
Therefore, the output is as follows −
2 Amar Delhi 4 Leena Nasik 6 Hema Nagpur 8 John Delhi 10 Raja NasikAdvertisements