Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django query __startswith is not case sensitive

I have been testing user searching with sorted results and I found this strange behavior

>>> User.objects.filter(username__istartswith="AbC")
<QuerySet [<User: AbC>, <User: AbCuuu>, <User: abc>, <User: abcuuu>]>
>>> User.objects.filter(username__startswith="AbC")
<QuerySet [<User: AbC>, <User: AbCuuu>, <User: abc>, <User: abcuuu>]>

Shouldn’t __startswith only have 2 of those results?
I need to actually search with case sensitivity, how do I do that?

I expect __startswith to be case sensitive and __istartswith to be case insensitive, but both return the same, case insensitive QuerySet

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are most likely using SQLite, where startswith will return the same result as istartswith, due to lack of case sensive LIKE (see text in bold at the bottom):

startswith

Case-sensitive starts-with.

Example:

Entry.objects.filter(headline__startswith='Lennon')

SQL equivalent:

SELECT ... WHERE headline LIKE 'Lennon%';

SQLite doesn’t support case-sensitive LIKE statements; startswith acts like istartswith for SQLite.

https://docs.djangoproject.com/en/4.1/ref/models/querysets/#startswith

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading