sql to sqlalchemy 转换的小例子
程序员文章站
2023-12-10 08:41:04
复制代码 代码如下:select to_char(date_published, 'yyyymm') yo from blog group by yo; 转换成sqlalc...
复制代码 代码如下:
select to_char(date_published, 'yyyymm') yo from blog group by yo;
转换成sqlalchemy 语句
可以使用 extract()
复制代码 代码如下:
in[3]: year_field = db.func.extract('year', articlemodel.date_published)
in[4]: month_field = db.func.extract('month', articlemodel.date_published)
in[5]: yonth_field = year_field *100+ month_field
in[6]:print db.session.query(yonth_field.label('yonth'), db.func.count(1)).group_by('yonth')
select extract(year from article_meta.date_published)*:param_1 + extract(month from article_meta.date_published)as yonth, count(:param_2)as count_1
from article_meta join article on article_meta.id = article.id groupby yonth
也可以 可以通过 func 直接调用数据库支持的函数或存储过程
复制代码 代码如下:
yonth = db.func.to_char(articlemodel.date_published,'yyyymm').label('yonth')
archive_list =(db.session.query(yonth,
db.func.count(1)).group_by('yonth').all())