how to have Accent-insensitive filter in django with postgres?

前端 未结 5 1766
挽巷
挽巷 2021-02-04 12:32

Hi I find that on postgres database, we can\'t configure default accent sensivity (on old mail exchanges).

Is there a way to have a _icontains also insensitive to specia

5条回答
  •  北海茫月
    2021-02-04 12:46

    I managed to install unaccent from postgresql contrib, but this answer that patches django didn't work. load_backend on django.db.utils enforces that the backend name starts with django.db.backends.

    The solution that worked for me was inserting this code in one of my modules:

    from django.db.backends.postgresql_psycopg2.base import DatabaseOperations, DatabaseWrapper
    
    def lookup_cast(self, lookup_type, internal_type=None):
        if lookup_type in('icontains', 'istartswith'):
            return "UPPER(unaccent(%s::text))"
        else:
            return super(DatabaseOperations, self).lookup_cast(lookup_type, internal_type)
    
    def patch_unaccent():
        DatabaseOperations.lookup_cast = lookup_cast
        DatabaseWrapper.operators['icontains'] = 'LIKE UPPER(unaccent(%s))'
        DatabaseWrapper.operators['istartswith'] = 'LIKE UPPER(unaccent(%s))'
        print 'Unaccent patch'
    
    patch_unaccent()
    

    Now unaccent searches are working fine, even inside django admin! Thanks for your answer above!

提交回复
热议问题