ben ben - 1 month ago 20
Python Question

Django - How to sort queryset by number of character in a field

MyModel:

name = models.CharField(max_length=255)


I try to sort the queryset. I just think about this:

obj = MyModel.objects.all().sort_by(-len(name)) #???


Any idea?

Answer

you might have to sort that in python..

sorted(MyModel.objects.all(),key=lambda o:len(o.name),reverse=True)

or I lied ( A quick google search found the following)

MyModel.objects.extra(select={'length':'Length(name)'}).order_by('length')
Comments