[Django]-Does Django's 'exact' field lookup perform a case-insensitive search?

2๐Ÿ‘

โœ…

Thanks to all for the answers. Indeed, Iโ€™ve realized that I use MySQL (MariaDB) with collation utf8mb4_unicode_ci, which explains why the exact query lookup works case-insensitively.

Without changing the collation of the underlying database (or some of its columns specifically), as pointed out, the following search is case-sensitive FormZBaseElementExtraLabel.objects.filter(label__contains = 'his6').filter(label = 'his6'). Alternatively, one could run a custom query using the raw method as explained here.

๐Ÿ‘คNicola Zilio

1๐Ÿ‘

Actually __exact is for Exact match

And __iexact is for Case-insensitive exact match

for more info you can visit the django documentation queryset page

๐Ÿ‘คNj Nafir

0๐Ÿ‘

Try this:
To case-SENSITIVE search

FormZBaseElementExtraLabel.objects.filter(**{'label__contains': 'his6'})

0๐Ÿ‘

I made this one which utilizes BINARY expr for MySQL string case-sensitive match:

from django.db.models.fields import Field
from django.db.models import Lookup

@Field.register_lookup
class StrExact(Lookup):
    """
    MySQL string case sensitive string lookup
    """

    lookup_name = 'str_exact'

    def as_sql(self, compiler, connection):
        lhs, lhs_params = self.process_lhs(compiler, connection)
        rhs, rhs_params = self.process_rhs(compiler, connection)
        params = lhs_params + rhs_params
        return "%s = binary %s" % (lhs, rhs), params

Usage:

FormZBaseElementExtraLabel.objects.filter(label__str_exact='his6').count()

Read more about Custom Lookup https://docs.djangoproject.com/en/3.0/howto/custom-lookups/

๐Ÿ‘คtrungnnh

Leave a comment