27👍
✅
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')
34👍
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())
- [Django]-Difference between setattr and object manipulation in python/django
- [Django]-Django: How to get related objects of a queryset?
- [Django]-Filter foreignkey field in django admin
8👍
You can of course sort the results using Python’s sorted
, but that’s not ideal. Instead, you could try this:
MyModel.objects.extra(select={'length':'Length(name)'}).order_by('length')
- [Django]-Adding django admin permissions in a migration: Permission matching query does not exist
- [Django]-Django TypeError: argument of type 'PosixPath' is not iterable
- [Django]-ImproperlyConfiguredError about app_name when using namespace in include()
5👍
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
.
- [Django]-How to display all session keys and values in Django?
- [Django]-Django / file uploads permissions
- [Django]-Update all models at once in Django
Source:stackexchange.com