- ru
- Language: en
- Documentation version: 2.0
2. How to order a queryset in case insensitive manner?
Whenever we try to do order_by
with some string value, the ordering happens alphabetically and w.r.t case. Like
>>> User.objects.all().order_by('username').values_list('username', flat=True)
<QuerySet ['Billy', 'John', 'Radha', 'Raghu', 'Ricky', 'Ritesh', 'johny', 'johny1', 'paul', 'rishab', 'sharukh', 'sohan', 'yash']>
If we want to order queryset in case insensitive manner, we can do like this .
.. code-block:: ipython
>>> from django.db.models.functions import Lower
>>> User.objects.all().order_by(Lower('username')).values_list('username', flat=True)
<QuerySet ['Billy', 'John', 'johny', 'johny1', 'paul', 'Radha', 'Raghu', 'Ricky', 'rishab', 'Ritesh', 'sharukh', 'sohan', 'yash']>
Alternatively, you can annotate with Lower
and then order on annotated field.
User.objects.annotate(
uname=Lower('username')
).order_by('uname').values_list('username', flat=True)