解决 sqlalchemy报Textual SQL expression should be explicitly declared as text的错误

1. 现象

执行某句sql的时候报错

Textual SQL expression 'template_type desc'  should be explicitly 
declared as text('template_type desc')

2. 原因

检查我们的python包依赖,发现之前使用的 sqlalchmy 版本为 1.2.x,现在使用的版本为1.3.x,问题出现在这里吗?
检查版本更新记录,在sqlalchemy 1.3 的 Key Changes - Core 部分发现 text() 处有改动,原来 sqlalchemy 在 1.3.x 之后 string SQL 由warning 变成了 Coercion,

The warnings that were first added in version 1.0, described 
at Warnings emitted when coercing full SQL fragments into text(), 
have now been converted into exceptions

也就是说1.3 之前使用如 order_by("template_type desc")这种方式只是会报警告的信息,但是在1.3之后的这种写法就会 raise CompileError

3. 解决方法

将写法由 order_by("template_type desc") 改为 order_by(text("template_type desc"))

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容