Search code examples
mysqldjangocase-insensitive

Django/MySQL - __istartswith not producing case-insensitive query


I make use of generic views and I am attempting to query my MySQL db (utf8_bin collation) in a case insensitive manor to try to find all my song titles that start with a particular letter.

view.py

def tracks_by_title(request, starts_with):
    return object_list(
        request,
        queryset = Track.objects.filter(title__istartswith=starts_with),
        template_name = 'tlkmusic_base/titles_list.html',
        template_object_name = 'tracks',
        paginate_by = 25,
    )

and my

urls.py

urlpatterns = patterns('tlkmusic.apps.tlkmusic_base.views',
    (r'^titles/(?P<starts_with>\w)/$', tracks_by_title),
)

the query it produces according to the django debug toolbar is:

SELECT `tracks`.`id`, `tracks`.`url`, `tracks`.`artist`, `tracks`.`album`, `tracks`.`genre`, `tracks`.`year`, `tracks`.`title`, `tracks`.`comment`, `tracks`.`tracknumber`, `tracks`.`discnumber`, `tracks`.`bitrate`, `tracks`.`length`, `tracks`.`samplerate`, `tracks`.`filesize`, `tracks`.`createdate`, `tracks`.`modifydate` FROM `tracks` WHERE `tracks`.`title` LIKE a% LIMIT 1

specifically this line:

WHERE `tracks`.`title` LIKE a% LIMIT 1

Why is it not case-insensitive which is what I was expecting by using __istartswith?

I am using Django 1.1.1 on Ubuntu.

EDIT

Running SELECT * FROM tracks WHERE title LIKE 'a%' LIMIT 0 , 30 in phpmyadmin still returns case-sensitive results, changing my collation is something I want to avoid mostly because the database is maintained by Amarok and I don't know the results of changing the collation on it's end.


Solution

  • MySQL does not support ILIKE.

    By default MySQL's LIKE compares strings case-insensitively.

    Edit:
    Thanks to the OP for providing additional information about the collation.
    The current collation, utf8_bin is case-sensitive.
    In contrast, utf8_general_ci is case-insensitive.

    It's probably easiest to modify collation.
    Something like this:

    ALTER TABLE `mydb`.`mytable` 
    MODIFY COLUMN `song_title` VARCHAR(254) 
    CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL;