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

+3


source to share


2 answers


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)

      

+1


source


One solution is to use annotate

lowercase to create a new field, then use distinct

.

Try something like



from django.db.models.functions import Lower

(people.exclude(twitter_handle=None)
      .annotate(handle_lower=Lower('twitter_handle'))
      .distinct('handle_lower'))

      

0


source







All Articles