I am using this django query
people.exclude(twitter_handle=None).distinct('twitter_handle').values_list('twitter_handle', flat=True)
My distinct query is returning two objects For example :
['Abc','abc']
How can i get case insensitive results ? like in this case only
['abc']
using django 1.9.6, python 2.7
We can use a distinct () query method at the end or in between queryset and with other regular Django query methods like all (), values (), etc… 3. Let's see some examples a). I created a simple model called user. b) Loaded the sample data to the user model and it looks like the below.
MongoDB query with case insensitive search? MongoDB query with case insensitive search? For case, insensitive search, use regex in find () method. Following is the syntax − To understand the above syntax, let us create a collection with documents −
Django’s QuerySet API provides a comprehensive array of methods and functions for working with data. In this section of the chapter, we’re going to look at all the common QuerySet methods, field lookups and aggregate functions, as well as building more complex queries with query expressions and Q () objects. Filter by the given lookup parameters.
The main downside is that if you refer to some table alias of the queryset in the raw SQL, then it is possible that Django might change that alias (for example, when the queryset is used as a subquery in yet another query). You should be very careful whenever you use extra ().
You can use .annotate()
along with Func() expressions
to apply .distinct()
on lowercased twitter_handle
value:
>>> from django.db.models.functions import Lower
>>> people.order_by().exclude(twitter_handle=None).annotate(handle_lower=Lower("twitter_handle")).distinct("handle_lower")
You can't append values_list('twitter_handle', flat=True)
to the above query because you can't apply distinct
on a field that doesn't exist in the values_list
so you have to do it by 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 lowercased twitter_handle
values:
>>> people.order_by().exclude(twitter_handle=None).annotate(handle_lower=Lower("twitter_handle")).distinct("handle_lower").values_list("handle_lower", flat=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With