比如要搜索一个列的字段长度,并倒序方式排列
方法1:原样写出自定义列的计算方式
order_by(fn.LENGTH(MyModel.my_field).desc())
# 或
order_by(fn.LENGTH(MyModel.my_field).alias('field_length').desc())
from peewee import Model, SqliteDatabase, CharField, fn
# 创建数据库连接
db = SqliteDatabase('my_database.db')
# 定义模型
class MyModel(Model):
my_field = CharField()
class Meta:
database = db
# 连接数据库并创建表
db.connect()
db.create_tables([MyModel])
# 插入一些数据
MyModel.create(my_field='abc')
MyModel.create(my_field='defg')
MyModel.create(my_field='hijkl')
# 查询并返回字段长度
query = MyModel.select(fn.LENGTH(MyModel.my_field).alias('field_length')).order_by(fn.LENGTH(MyModel.my_field).desc())
# 打印结果
for row in query:
print(row.field_length)
方法2:通过别名,拼接sql语句
order_by(SQL('field_length DESC'))
from peewee import Model, SqliteDatabase, CharField, fn, SQL
# 创建数据库连接
db = SqliteDatabase('my_database.db')
# 定义模型
class MyModel(Model):
my_field = CharField()
class Meta:
database = db
# 连接数据库并创建表
db.connect()
db.create_tables([MyModel])
# 插入一些数据
MyModel.create(my_field='abc')
MyModel.create(my_field='defg')
MyModel.create(my_field='hijkl')
# 查询并返回字段长度
query = MyModel.select(fn.LENGTH(MyModel.my_field).alias('field_length')).order_by(SQL('field_length DESC'))
# 打印结果
for row in query:
print(row.field_length)