5

I'm really new to django, python and postgres... I can't seem to find the answer on how to order_by being case insensitive while using Model as the query method, only if you use direct SQL queries.

Model
@classmethod
def get_channel_list(cls, account):
    return cls.objects.filter(accountid=account).order_by('-name').values_list('name', 'channelid')

Data set and order it's currently being ordered in

test
b test
a test channel
a test channel
a test 2 
a b test
Test Channel
Test 3
Test 3
Test 2 Channel

any help would be much appreciated.

2 Answers 2

22

With django 1.8, there is a built-in solution:

from django.db.models.functions import Lower
...
ret = ret.order_by(Lower('name_lower'))
ret = ret.order_by(Lower('name_lower').asc())
ret = ret.order_by(Lower('name_lower').desc())
Sign up to request clarification or add additional context in comments.

2 Comments

@Sven I would agree if my question wasn't specifically directed towards Django 1.5.3 (and not 1.8+)
This works when you're talking about sorting on just one column or multiple columns all in one direction. But, what if you need to sort multiple columns, some ascending and some descending? (e.g. I'm selecting 4 columns and I want it sorted ascending by col 1 and, secondarily, descending by col 3)
1

Using QuerySet.extra(select=...):

@classmethod
def get_channel_list(cls, account):
    ret = cls.objects.extra(select={'name_lower': 'lower(name)'})
    ret = ret.order_by('-name_lower')
    ret = ret.filter(accountid=account).values_list('name', 'channelid')
    return channels

15 Comments

If I do that, I get the following error Cannot resolve keyword 'name_lower' into field. Choices are: accountid, active, channelid, id, name
@AndrewWilson, You don't need to add extra field to the model. See this screencast I just recorded.
That for some reason doesn't work for me in Django 1.5.3 and Python 2.7, not sure if it's a version thing
@AndrewWilson, Try select name from appname_modelname order by lower(name); in dbshell . Does it work?
it returns the list of names without lowercasing the name in the correct order. Using Postgresql 9.3
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.