25👍
✅
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
115👍
Since Django 1.8 it is possible with:
from django.db.models.functions import Lower
MyModel.objects.order_by(Lower('myfield'))
- [Django]-Unable to find a locale path to store translations for file __init__.py
- [Django]-Django ImportError: cannot import name 'render_to_response' from 'django.shortcuts'
- [Django]-Class Based Views VS Function Based Views
2👍
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.
- [Django]-Dropdown in Django Model
- [Django]-Django – How to rename a model field using South?
- [Django]-Get request data in Django form
Source:stackexchange.com