Jack Evans
Jack Evans

Reputation: 1717

Django case insensitive in check against list

My site has a bunch of Thread objects

  >>> Thread.objects.filter(board__name='Fitness')
    [<Thread: lorem>, <Thread: lorems>, <Thread: LOREM>]

And each user has a list of filters, (Postgresql Array Field)

>>> filters
['lorem', 'adipisci', 'amet', 'dolor']

I want be to able to exclude threads that are in the users filter list. So far this is the only way I've been able to achieve this:

>>> Thread.objects.filter(board__name='Fitness').exclude(reduce(operator.or_, (Q(title__icontains=x) for x in filters)))
[]

I'm wondering if there's a way to do case insensitive checks in Django with the in operator. Since the below does not work

>>> Thread.objects.filter(board__name='Fitness').exclude(title__in=filters)
[<Thread: lorems>, <Thread: LOREM>]

Preferably from within Django, and not having to mess with the Database itself

Upvotes: 1

Views: 589

Answers (1)

NS0
NS0

Reputation: 6106

You can try using iregex, in the following way:

>>> Thread.objects.filter(board__name="Fitness") \
                  .exclude(title__iregex=r"(" + "|".join(filters) + ")$")
[<Thread: lorems>]

Upvotes: 1

Related Questions