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