简体   繁体   English

如何通过 python SQLAlchemy 中的 substring 订购

[英]How to order by substring in python SQLAlchemy

I'm using SQLAlchemy for my python script, and I am unable to order the select query in asc order based on a substring column value.我将 SQLAlchemy 用于我的 python 脚本,并且我无法根据 ZE83AED2DBBDF00BEC67 列值 select 以升序顺序订购 select 查询。

The actual query is this one实际查询是这个

books = Book.order_by(Book.id.asc(), Book.title.asc()).all()

but I want to order by a substring of the first 4 digits of the title column.但我想按title列前 4 位数字的 substring 订购。

In SQL language I would do so在 SQL 语言中我会这样做

SELECT * 
FROM book
ORDER BY id asc, substring(title,0,5) asc;

but in SQLAlchemy?但在 SQLAlchemy 中?

tnx tnx

You can use the function substr:您可以使用 function 子字符串:

from sqlachemy import func
books = Book.order_by(Book.id.asc(), func.substr(Book.title, 1, 4).asc()).all()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM