开发者

django-orm case-insensitive order by

开发者 https://www.devze.com 2023-01-10 18:29 出处:网络
I know, I can run a case insensitive search from DJango ORM. Like, User.objects.filter(first_name__contains=\"jake\")

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 th开发者_JS百科em 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消