[Answered ]-How to get objects in case insensitive order using model manager method in django

2👍

You can also use extra:

Organization.objects.extra(select={'lower_name':'lower(name)'}).order_by('lower_name')

django-orm case-insensitive order by

Edit:

Please check that

Organization.objects.extra(select={'lower_name':'lower(administrator__name)'}).order_by('lower_name')

0👍

There’s a clear distinction what you should do in model and what in model manager. Basically, models should only contain methods that deal with single instance, while custom model managers should be used to contain any logic that operates on model lists or do custom queries.

So, in your example this should look like:

class OrganizationManager(models.Manager):
    def insensitive(self):
        return self.all().extra(select={'name_lower': 'lower(name)'}, order_by=['name_lower'])

class Organization(models.model):
    objects = OrganizationManager()

And you can use it like

orgs_insensitive = Organization.objects.insensitive()

Refer to django model manager docs for details.

EDIT: turns out django does not support filter field lookups for order, so according to the last comment on this ticket, case insensitive ordering should be done like

my_model.objects.all().extra(select={'imf': 'UPPER(my_field)'}, order_by=['imf'])
👤J0HN

0👍

it possible to get case insensitive objects based on foreign key attribute (like administrator mentioned above) using raw query.

Organization.objects.raw('select * from organization o,auth_user a on o.administrator_id=a.id order by a.username COLLATE NOCASE ASC')
👤Ravi

Leave a comment