Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django case insensitive "distinct" query

Tags:

python

orm

django

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

like image 586
Daniyal Syed Avatar asked Jun 02 '17 15:06

Daniyal Syed


People also ask

How to use distinct() query method in Django?

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.

How to query with case insensitive search in MongoDB?

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 −

What is the use of queryset in Django?

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.

What are the downsides of using an extra query in Django?

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 ().


Video Answer


1 Answers

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)
like image 106
Ozgur Vatansever Avatar answered Oct 04 '22 00:10

Ozgur Vatansever