简体   繁体   中英

Django __exact queryset filter - case sensitivity not working as expected

I am trying to filter a Django queryset where the case should be sensitive, although I am not getting the results I expect from the "__exact" filter, which I believe to be case-sensitive: https://docs.djangoproject.com/en/3.0/ref/models/querysets/

My code looks like this:

lower_case_test = MyObject.objects.filter(name__exact="d")
for item in lower_case_test:
    print("item.name: ", item.name)

I have 2 in the "MyObject" model, one with name "d" and one with name "D".

The output of the above code is:

(u'item: ', u'D') (u'item: ', u'd')

Can anyone suggest what might be the issue here? Thanks in advance.

I supposed you made a typo in the filter because it should be two underscores between name and exact .

Some database cannot do exact match on strings and will answer you results in any lower/upper-cases.

What is you database and database config?

More info in django note

You can find out by doing your query in django shell ( ./manage.py shell ) and ask for the sql statements:

from logging import getLogger, DEBUG, StreamHandler
l = getLogger('django.db.backends')
l.setLevel(DEBUG)
# l.addHandler(StreamHandler())  # shouldn’t be necessary
list(MyObject.objects.filter(name__exact="d"))

With this, you can try to play it directly in your database and better understand what's going on (you can use ./manage.py dbshell )

The __exact and __iexact queries are case insensitive if you are using the SQLLite DB.

To get the functionally correctly, change the Collation of the MySql database to latin1_swedish_cs or utf8_bin for case sensitive comparisons.

Check the link for detailed solution. https://code.djangoproject.com/ticket/2170

let's consider your model MyObject and it has a field name

The first thing here you made an error, a typo. The lookup types should be starts with __ symbol(double underscore)

So your Query should be like name__exact

and let us consider there are elements in the DB one with name = 'D' and other with name = 'd'

So, we've two lookup types exact and iexact.

print(MyObject.objects.filter(name__iexact='D').values_list('name',flat=True))

will give the output D,d

print(MyObject.objects.filter(name__exact='D').values_list('name',flat=True))

will give the output D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM