Proposal: filter by multiple values, case-insensitive

387 views
Skip to first unread message

Jeremy Nauta

unread,
Oct 29, 2022, 9:02:38 AM10/29/22
to Django developers (Contributions to Django itself)
Hi all, I'd like to propose a new django filter: __iin. As the name implies, this filter finds results that match one of the given values, ignoring case. In other words, this is a hybrid of __in and __iexact.

It surprises me that there are filters for qs.filter(field__iexact='text')qs.filter(field__icontains='text'), and qs.filter(field__in=['text']), yet there is no qs.filter(field__iin=['text']) filter.

I've made a POC for this field in postgres and it seems quite straightforward. I'd be happy to try porting into the Django codebase, but first I wanted to see if there is interest and/or feedback! Please let me know what you think.


from django.db.models import Field
from django.db.models.lookups import In


@Field.register_lookup
class IIn(In):
    """
    Case-insensitive version of `__in` filters. Adapted from `In` and `IExact` transformers.
    """

    lookup_name = 'iin'

    def process_lhs(self, *args, **kwargs):
        sql, params = super().process_lhs(*args, **kwargs)

        sql = f'LOWER({sql})'

        return sql, params

    def process_rhs(self, qn, connection):
        rhs, params = super().process_rhs(qn, connection)

        params = tuple(p.lower() for p in params)

        return rhs, params

Adam Johnson

unread,
Nov 2, 2022, 4:10:43 PM11/2/22
to django-d...@googlegroups.com
This can currently be achieved with:

qs.annotate(lowername=Lower("name")).filter(lowername__in=['text'])

You’re free to add “iin” to your projects, but I'm not sure it's valuable enough to add to Django.

Some years ago, there was an idea to allow python expressions to generate ORM filters, that would allow your lookup to done without any extensions: https://github.com/django/django/pull/12041 .

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/bf623b99-9032-4ada-9739-ef63f2982e6an%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages