Peewee 简明教程
Peewee - User defined Operators
Peewee 拥有 Expression 类,借助该类,我们可以向 Peewee 的运算符列表中添加任何自定义运算符。Expression 的构造函数需要三个参数,左操作数、运算符和右操作数。
Peewee has Expression class with the help of which we can add any customized operator in Peewee’s list of operators. Constructor for Expression requires three arguments, left operand, operator and right operand.
op=Expression(left, operator, right)
使用 Expression 类,我们定义一个 mod() 函数,它接受 left 和 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
我们可以在 SELECT 查询中使用它来获取 Contacts 表中 id 为偶数的记录列表。
We can use it in a SELECT query to obtain list of records in Contacts table with even id.
from peewee import *
db = SqliteDatabase('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)
此代码将发出由以下字符串表示的 SQL 查询 −
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])