Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-orm case-insensitive order by

I know, I can run a case insensitive search from DJango ORM. Like,

User.objects.filter(first_name__contains="jake")
User.objects.filter(first_name__contains="sulley")
User.objects.filter(first_name__icontains="Jake")
User.objects.filter(first_name__icontains="Sulley")

And also, I can fetch them as

user_list = User.objects.all().order_by("first_name")
# sequence: (Jake, Sulley, jake, sulley)
user_list = User.objects.all().order_by("-first_name") # for reverse
# sequence: (sulley, jake, Sulley, Jake)

Is there a direct way for a case-insensitive fetch?? As in I want a sequence as

# desired sequence: jake, Jake, sulley, Sulley

If not, then suggest a best way to do it. Thanks in advance.

like image 337
simplyharsh Avatar asked Aug 04 '10 19:08

simplyharsh


3 Answers

Since Django 1.8 it is possible with:

from django.db.models.functions import Lower
MyModel.objects.order_by(Lower('myfield'))

https://code.djangoproject.com/ticket/6498

like image 96
uri.z Avatar answered Nov 19 '22 22:11

uri.z


This answer is outdated, follow top voted solution with django >= 1.8

I found solution using .extra

class MyModelName(models.Model):
   is_mine = models.BooleanField(default=False)
   name = models.CharField(max_length=100)


MyModelName.objects.filter( is_mine=1 ).extra(\
    select={'lower_name':'lower(name)'}).order_by('lower_name')

original link:

http://naorrosenberg.blogspot.fi/2011/04/django-models-orderby-charfield-case.html

like image 27
Troyhy Avatar answered Nov 20 '22 00:11

Troyhy


Lets take an example where you have to do a case insensitive order by of the field "first_name" from the User Model

# Importing the Lower Function
from django.db.models.functions import Lower


#For ordering by Ascending order
User.objects.all().order_by(Lower('first_name'))

#For ordering by Descending order
User.objects.all().order_by(Lower('first_name').desc())

The Lower function converts all the "first_name" values into lowercase, and then it's ordered accordingly.

like image 1
Ranjan MP Avatar answered Nov 20 '22 00:11

Ranjan MP