django-orm case-insensitive order by

DjangoCase InsensitiveFetchDjango Orm

Django Problem Overview


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.

Django Solutions


Solution 1 - Django

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

Solution 2 - Django

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

Solution 3 - Django

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsimplyharshView Question on Stackoverflow
Solution 1 - Djangouri.zView Answer on Stackoverflow
Solution 2 - DjangoTroyhyView Answer on Stackoverflow
Solution 3 - DjangoRanjan MPView Answer on Stackoverflow