BOMBOLOM.COM

(django) Order_by using case insensitive

Posted by José Lopes

This post shows how you can sort a QuerySet assuring a case insensitive ordering.

In Django, when we use the order_by method on a QuerySet the result is case sensitive by default and there is no option to change it.

To assure that the result is case insensitive we can use the extra method, creating an extra attribute that takes the model field in question together with the LOWER or UPPER SQL functions and then orders by it:

MyModel.objects.all().extra(select={'my_order':'LOWER(model_field)'}).order_by('my_order')

The LOWER and UPPER SQL functions are available for the majority of the databases as we can see on the SQL dialects reference Wikibook.

Of course that we can use this solution with any QuerySet, I used the all method just for simplification.

In my opinion this is a clean solution. It can be use on any field of the model and doesn't pollutes the database with unnecessary information (if for instance we create an additional field, with a custom manager or overriding the model save method, to be used only for the ordering). It also avoids special configuration of the database to assure the same result.

2009.06.18 | There's more... | Comments 0 | Tags ,

Deixe a sua mensagem:

Nome:


E-mail:


URL:


Comment:

Secret number

To send you comment you must insert the "secret number" on the box


Made with PyBlosxom | Add to Google