Using Unaccent in Django Model database function

3.8k views Asked by At

I have the unaccent extension installed in Postgres and simple filters are working fine in my Django app, for example:

q = 'hello'
queryset.filter(name__unaccent__startswith=q)

I'm now trying to annotate the queryset result with the search index:

queryset.annotate(search_index=StrIndex(Lower('name'), Value(q)))

That works fine by itself for unaccented text, but I'm trying to figure out a way to apply UNACCENT to the name variable. Essentially:

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
  -- ...

I've tried:

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

I've seen this answer: How use `unaccent` with full text search in django 1.10? but feel like that shouldn't be needed.

1

There are 1 answers

0
getup8 On BEST ANSWER

After additional digging, I was able to just do this:

from django.contrib.postgres.lookups import Unaccent

queryset.annotate(search_index=StrIndex(Unaccent(Lower('name')), Value(q)))

Doesn't seem to be well documented in Django, but works as expected with SQL:

STRPOS(UNACCENT(LOWER("core_ingredient"."name")), 'hello') AS "search_index"