month_column = dc.Message.date_utc.month
year_column = dc.Message.date_utc.year
message_count = fn.Count(dc.Message.id)
yearmonthname_column = year_column.concat("_").concat(month_column).concat("_").concat(dc.User.name)
yearmonth_column = year_column.concat("_").concat(month_column)
query = (dc.Message
.select(yearmonthname_column.alias('yearmonthname'), yearmonth_column.alias('yearmonth'), dc.User.name, message_count.alias("messages_count"), year_column.alias("year"), month_column.alias("month"))
.join(dc.User)
.where(dc.Message.posted_in == chatId)
.group_by(yearmonthname_column)
.order_by(message_count.desc())
.order_by(month_column.cast('INTEGER')) # SORTING BY MONTH
.order_by(year_column)
)
上面,你可以看到我的查询。这里的问题是:我希望它按month
值排序,好像它是数字,但我看到的结果如下:
"1", "10", "11", "12", "2"
而不是:
"1", "2", "10", "11", "12"
按行进行按月排序:
.order_by(month_column.cast('INTEGER'))
正如您所看到的,我试图将此值转换为INTEGER
,但实际上并没有改变任何内容。
这个问题是否有任何简单的解决方法?
修改
我还注意到peewee生成的最终SQL代码中没有cast
。
我如何得到它:
print(query.sql())
它看起来如何:
('SELECT ((((date_part(?, "t1"."date_utc") || ?) || date_part(?, "t1"."date_utc")) || ?) || "t2"."name") AS yearmonthname, ((date_part(?, "t1"."date_utc") || ?) || date_part(?, "t1"."date_utc")) AS yearmonth, "t2"."name", Count("t1"."id") AS messages_count, date_part(?, "t1"."date_utc") AS year, date_part(?, "t1"."date_utc") AS month FROM "message" AS t1 INNER JOIN "user" AS t2 ON ("t1"."created_by_id" = "t2"."id") WHERE ("t1"."posted_in_id" = ?) GROUP BY ((((date_part(?, "t1"."date_utc") || ?) || date_part(?, "t1"."date_utc")) || ?) || "t2"."name") ORDER BY date_part(?, "t1"."date_utc")', ['year', '_', 'month', '_', 'year', '_', 'month', 'year', 'month', 220, 'year', '_', 'month', '_', 'year'])
这可能就是为什么它不起作用。有谁知道为什么会这样?
答案 0 :(得分:1)
Title: Tales from Shakespeare (1807)
Author: Shakespeare
Price: 6.74
Title: The Jungle Book (1894)
Author: Rudyard Kipling
Price: 9.99
Title: Through the Looking-Glass (1871)
Author: Lewis Carroll
Price: 12.97
仅适用于Peewee v3.0.0或更高版本。如果您使用的是v2.x,则必须使用.order_by(Message.month.cast('int'))
中的Cast()
。 .order_by(Cast(Message.month, 'int'))
方法添加了this commit。
这是一个有效的代码:
cast()