Gocht
Gocht

Reputation: 10256

Django - Query EXACT string match

I have a user in my DB with this value:

booking_id -> 25DgW

This field is marked as unique in my model

booking_id = models.CharField(null=False, unique=True, max_length=5, default=set_booking_id)

But now when I query for the user like this:

>>> User.objects.get(booking_id='25dgw')  # I think this should throw a DoesNotExist exacption
<User: John Doe>

Even if I do:

>>> Partner.objects.get(booking_id__exact='25dgw')
<User: John Doe>

I need a query that return the user only if the code is written exactly in the same way than is saved in database: 25DgW instead of 25dgw.

How should I query?

Upvotes: 1

Views: 7153

Answers (3)

Simoons
Simoons

Reputation: 81

User.objects.filter(booking_id='25dgw', booking_id__contains='25dgw').first() seems to work for me (result = None). The booking_id parameter is to assert the correct letters and no more, the booking_id__contains to assert the case sensitiveness.

Upvotes: 2

aprasanth
aprasanth

Reputation: 1099

By default, MySQL does not consider the case of the strings. There will be a character set and collation associated with the database/table or column.

The default collation for character set latin1, which is latin1_swedish_ci, which is case-insensitive. You will have to change the collation type to latin1_general_cs which supports case sensitive comparison.

You can to change character-set/collation settings at the database/table/column levels.

The following steps worked for me.

  1. Go to MySQL shell

    mysql -u user -p databasename

  2. Change character set and collation type of the table/column

    ALTER TABLE tablename CONVERT TO CHARACTER SET latin1 COLLATE latin1_general_cs;
    
  3. Now try the query

    Partner.objects.get(booking_id__exact='25dgw')
    

This throws an error, table matching query does not exist.

Reference - Character Sets and Collations in MySQL

Upvotes: 2

user42488
user42488

Reputation: 1455

This seems to work:

qs.filter(booking_id__contains='25DgW').first()

Upvotes: 0

Related Questions