pinq-
pinq-

Reputation: 389

Django case sensitive search

I have problem. I have model like this:

class Teams(models.Model):
    Name = models.CharField(max_length=200)
    Short_name = models.CharField(max_length=200, default = "-")

When I search team by short name, like "Har":

models.Teams.objects.filter(SHort_name = "Har")

I get results with "HAR" and "Har". Even if I try like this:

 models.Teams.objects.filter(SHort_name__exact = "Har"):

I get same results ("HAR" and Har") The Short_name column is in utf8mb4_general_ci format, so it should be ok and database connection has this options:

'OPTIONS': {'charset': 'utf8mb4', 'use_unicode': True},

I don't know what is wrong or how to get exact one result.

Upvotes: 0

Views: 206

Answers (2)

Gabriel
Gabriel

Reputation: 1149

Use utf8bin (or utf8mb4_bin) collation in your db, this did the trick for me in the past.

Hopes this helps.

Upvotes: -1

Matt S
Matt S

Reputation: 15374

Based on your question I assume you're using MySQL. When not using binary collation MySQL performs case insensitive string comparisons.

https://dev.mysql.com/doc/refman/8.0/en/case-sensitivity.html

Your issue is at the database level and Django couldn't work around it without converting collations on every query. Change your collation in utf8_bin (or another *_bin) and you'll be all set:

By default, with a UTF-8 database, MySQL will use the utf8_general_ci collation. This results in all string equality comparisons being done in a case-insensitive manner. That is, "Fred" and "freD" are considered equal at the database level... If you want case-sensitive comparisons on a particular column or table, change the column or table to use the utf8_bin collation.

https://docs.djangoproject.com/en/2.2/ref/databases/#collation-settings

Upvotes: 2

Related Questions