Django case insensitive "single" request
I am using this django request
people.exclude(twitter_handle=None).distinct('twitter_handle').values_list('twitter_handle', flat=True)
My separate query returns two objects For example:
['Abc','abc']
How can I get case-insensitive results? as in this case only
['abc']
using django 1.9.6, python 2.7
source to share
You can use .annotate()
together with Func() expressions
to apply .distinct()
to the bottom value twitter_handle
:
>>> from django.db.models.functions import Lower
>>> people.order_by().exclude(twitter_handle=None).annotate(handle_lower=Lower("twitter_handle")).distinct("handle_lower")
You cannot add values_list('twitter_handle', flat=True)
to the above query because you cannot apply distinct
to a field that does not exist in values_list
, so you have to do it yourself:
>>> queryset = people.order_by().exclude(twitter_handle=None).annotate(handle_lower=Lower("twitter_handle")).distinct("handle_lower")
>>> [p.twitter_handle for p in queryset]
or you can get the bottom values twitter_handle
:
>>> people.order_by().exclude(twitter_handle=None).annotate(handle_lower=Lower("twitter_handle")).distinct("handle_lower").values_list("handle_lower", flat=True)
source to share