Ravi
Ravi

Reputation: 157

how to get objects in case insensitive order using model manager method in django

i want to display objects in case insensitive order

for eg

class Organization(models.model):
    name=models.CharField(max_length=50)
    administrator = models.ForeignKey(User, blank=True,related_name = 'OrgAdmin')
    types = models.ManyToManyField(OrganizationType,blank=True, null=True)

to display objects ordered by name

Organization.objects.all().order_by('name')

will display in case sensitive

soo what will be option for case insensitive order

how we can achieve this using model method

Upvotes: 1

Views: 1096

Answers (3)

Ravi
Ravi

Reputation: 157

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')

Upvotes: 0

Silwest
Silwest

Reputation: 1620

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')

Upvotes: 2

J0HN
J0HN

Reputation: 26941

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'])

Upvotes: 0

Related Questions