在 Django Model 数据库函数中使用 Unaccent

get*_*up8 4 python django

unaccent在 Postgres 中安装了扩展,并且简单的过滤器在我的 Django 应用程序中运行良好,例如:

q = 'hello'
queryset.filter(name__unaccent__startswith=q)
Run Code Online (Sandbox Code Playgroud)

我现在尝试使用搜索索引注释查询集结果:

queryset.annotate(search_index=StrIndex(Lower('name'), Value(q)))
Run Code Online (Sandbox Code Playgroud)

对于非重音文本来说,这本身就很好用,但我正在尝试找出一种将 UNACCENT 应用于 name 变量的方法。本质上:

SELECT
  -- This is what I want!
  STRPOS(LOWER(UNACCENT(core_ingredient.name)::text), 'hello') AS search_index_unaccented,
  STRPOS(LOWER(core_ingredient.name), 'hello') AS search_index_basic
FROM
  -- ...
Run Code Online (Sandbox Code Playgroud)

我试过了:

# This has no effect, gives same query / result as above
queryset.annotate(search_index=StrIndex(Lower('name__unaccent'), Value(q)))
Run Code Online (Sandbox Code Playgroud)

我看过这个答案: How use `unaccent` with full text search in django 1.10? 但感觉不需要那样。

get*_*up8 5

经过额外的挖掘,我能够做到这一点:

from django.contrib.postgres.lookups import Unaccent

queryset.annotate(search_index=StrIndex(Unaccent(Lower('name')), Value(q)))
Run Code Online (Sandbox Code Playgroud)

Django 中似乎没有详细记录,但在 SQL 中可以按预期工作:

STRPOS(UNACCENT(LOWER("core_ingredient"."name")), 'hello') AS "search_index"
Run Code Online (Sandbox Code Playgroud)