我在 Postgres 中安装了 unaccent
扩展,并且简单的过滤器在我的 Django 应用程序中运行良好,例如:
q = 'hello'
queryset.filter(name__unaccent__startswith=q)
我现在尝试使用搜索索引注释查询集结果:
queryset.annotate(search_index=StrIndex(Lower('name'), Value(q)))
对于非重音文本来说,这本身就可以很好地工作,但我正在尝试找出一种将 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
-- ...
我已经尝试过:
# This has no effect, gives same query / result as above
queryset.annotate(search_index=StrIndex(Lower('name__unaccent'), Value(q)))
我看过这个答案: How use `unaccent` with full text search in django 1.10?但感觉不需要那样。
最佳答案
经过额外的挖掘,我能够做到这一点:
from django.contrib.postgres.lookups import Unaccent
queryset.annotate(search_index=StrIndex(Unaccent(Lower('name')), Value(q)))
在 Django 中似乎没有很好的记录,但在 SQL 中可以按预期工作:
STRPOS(UNACCENT(LOWER("core_ingredient"."name")), 'hello') AS "search_index"
关于python - 在 Django Model 数据库函数中使用 Unaccent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59603507/