使用 peewee ORM 在带有 table 字段的字符串文字中搜索
Search in a string literal with a table field with peewee ORM
我正在尝试查找某个字段与作为固定参数提供的字符串文字的开头相匹配的所有记录。 needle 是来自 table.
的字段
例子:给定一个参数'John Doe',我想得到table用户的所有记录,其中first_name字段是开头的子串该 'John Doe' 字符串的匹配记录(例如,匹配记录将是 first_name 为 'John' 或 'Jo' 或 'Joh' 等的记录
看来我可以通过以下 SQL:
SELECT * FROM user WHERE 'John Doe' LIKE first_name || '%'
现在如何将其翻译成 peewee?奇怪的是,我实际上能够为此获得正确的 SQL 但由于某种原因,当我通过 SQLite 命令行直接输入相同的查询时,peewee 返回一个空结果。
User.select().where(SQL("'John Doe'").startswith(User.first_name))
当我检查这个的sql()
时,它显示:
('SELECT "t1"."id", "t1"."first_name" FROM "user" AS "t1" WHERE ("John Doe" LIKE ("t1"."first_name" || ?))', ['%'])
但是结果是空的。同样SQL在命令行returns正确的记录...我做错了什么?
我会这样写:
User.select().where(Value('John Doe') ** (User.first_name + '%'))
求幂重载转换为不区分大小写的 LIKE。
我正在尝试查找某个字段与作为固定参数提供的字符串文字的开头相匹配的所有记录。 needle 是来自 table.
的字段例子:给定一个参数'John Doe',我想得到table用户的所有记录,其中first_name字段是开头的子串该 'John Doe' 字符串的匹配记录(例如,匹配记录将是 first_name 为 'John' 或 'Jo' 或 'Joh' 等的记录
看来我可以通过以下 SQL:
SELECT * FROM user WHERE 'John Doe' LIKE first_name || '%'
现在如何将其翻译成 peewee?奇怪的是,我实际上能够为此获得正确的 SQL 但由于某种原因,当我通过 SQLite 命令行直接输入相同的查询时,peewee 返回一个空结果。
User.select().where(SQL("'John Doe'").startswith(User.first_name))
当我检查这个的sql()
时,它显示:
('SELECT "t1"."id", "t1"."first_name" FROM "user" AS "t1" WHERE ("John Doe" LIKE ("t1"."first_name" || ?))', ['%'])
但是结果是空的。同样SQL在命令行returns正确的记录...我做错了什么?
我会这样写:
User.select().where(Value('John Doe') ** (User.first_name + '%'))
求幂重载转换为不区分大小写的 LIKE。