SELECT name from distributors_distributor ORDER BY LENGTH(name)
Instead of writing raw SQL in my view, I am doing this:
names = [x['name'] for x in Distributor.objects.values('name')]
names.sort(lambda x, y: len(x) - len(y))
Is there a better way of doing this? Or rather, is there a way to use
the QuerySet API to produce the equivalent of the SQL above?
Something like this should work:
Distributor.objects.extra(select={'length':'Length(name)'}).order_by('length')
This uses an extra() clause to add a length field to the select that
is being retrieved, then uses that length column for sorting purposes.
It does involve a little raw SQL leaking through to your code (the
call to Length()), but not as much as a completely raw SQL query would
require.
This class of problem could also be addressed by the F() notation that
has been proposed in #7210 and accepted for v1.1. This particular use
case wasn't on the original todo list, but it should be in the realms
of possibility.
Yours,
Russ Magee %-)