Skip to content Skip to sidebar Skip to footer

Case Insensitive Search In Django For Mysql

I'm trying to do a case insensitive search for a substring within a field in my model. My model: class doctor(models.Model): docid = models.AutoField(primary_key=True, unique=T

Solution 1:

As pointed out in the django docs,

In MySQL, a database table’s “collation” setting determines whether exact comparisons are case-sensitive. This is a database setting, not a Django setting. It’s possible to configure your MySQL tables to use case-sensitive comparisons, but some trade-offs are involved. For more information about this, see the collation section in the databases documentation.

In my case, I solved it with

from django.db.models import Q,CharField
from django.db.models.functions import Lower
CharField.register_lookup(Lower, "lower")
doctor.objects.filter(Q(name__lower__contains='joel'))

The tip in this regard was provided by Matthew Pava from the django-users mailing list.

Post a Comment for "Case Insensitive Search In Django For Mysql"