Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case sensitive search in Django, but ignored in Mysql

I have a field in a Django Model for storing a unique (hash) value. Turns out that the database (MySQL/inno) doesn't do a case sensitive search on this type (VARCHAR), not even if I explicitly tell Django to do a case sensitive search Document.objects.get(hash__exact="abcd123"). So "abcd123" and "ABcd123" are both returned, which I don't want.

class document(models.Model):
   filename    = models.CharField(max_length=120)
   hash        = models.CharField(max_length=33 )

I can change the 'hash field' to a BinaryField , so in the DB it becomes a LONGBLOB , and it does do a case-sensitive search (and works). However, this doesn't seem very efficient to me. Is there a better way (in Django) to do this, like adding 'utf8 COLLATE'? or what would be the correct Fieldtype in this situation? (yes, I know I could use PostgreSQL instead..)

like image 704
Alex Avatar asked Jan 21 '15 18:01

Alex


1 Answers

The default collation for character set for MySQL is latin1_swedish_ci, which is case insensitive. Not sure why that is. But you should create your database like so:

CREATE DATABASE database_name CHARACTER SET utf8;
like image 154
dan-klasson Avatar answered Oct 14 '22 01:10

dan-klasson