Django - How to sort queryset by number of character in a field
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)) #???
you might have to sort that in python..
or I lied ( A quick google search found the following)
The new hotness (as of Django 1.8 or so) is Length()
from django.db.models.functions import Length obj = MyModel.objects.all().order_by(Length('name').asc())
You can of course sort the results using Python's sorted, but that's not ideal. Instead, you could try this:
You'll need to use the extra argument to pass an SQL function:
obj = MyModel.objects.all().extra(order_by=['LENGTH(`name`)'])
Note that this is db-specific: MySQL uses LENGTH, others might use LEN.