10

In the Django documentation for ArrayField, it lists a contains field lookup. However, no icontains (case insensitive lookup - many other fields have it) lookup is present in ArrayField.

I need a case-insensitive lookup function for ArrayField, similar to the pre-existing contains lookup.

3 Answers 3

8

warning: this is a hack and led to a bug in my own app. Use at your own risk.


You can do a case-insensitive look-up using icontains, by omitting the square brackets you would use for contains:

queryset = my_model.objects.filter(field_name__icontains='my_substring')

This works because Postgres casts the ArrayField to text and then checks for 'my_substring' as a substring of the array's text representation. You can see this by examining the resulting query:

print(queryset.query)

# raw SQL output:
'SELECT ... WHERE UPPER("my_model"."field_name"::text) LIKE UPPER(%my_substring%)

This worked for me in Postgres 10.1.


addendum/bug

This approach caused a bug for my project. Say you want to check if the array field contains 'my_substring':

field_name__icontains='my_substring'

This will retrieve 'my_substring', but it will also retrieve 'foo_my_substring'. This has to do with the string casting mentioned above. Use at your own risk.

2
  • I tried to query for gender with this and it returned both female with male lol Dec 8, 2022 at 0:38
  • Be careful! This does not answer the original question, and as Stevula acknowledges at the end of his answer, it will indeed even cause a bug if the table has other strings containing the string you're looking for. @quick answer should be used instead.
    – GuiTeK
    Apr 26 at 10:46
4

icontains, iexact are only applied on string type:

my_array_field__contains=['H'] 

check if ['H'] is included in my_array_field

But if you try the following, it will works:

my_array_field__0__icontains='H'

because it check if the first element contains H or h

0
3

You can query case-insensive search for array like this:

select 'tartu' ILIKE ANY (array['Tallinn', 'Tartu','Narva']);

In Django:

MyModel.objects.extra(
    where=['%s ILIKE ANY (array_column_name)'],
    params=['tartu', ]
)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.