order by field length?

854 views
Skip to first unread message

David Lindquist

unread,
Dec 16, 2008, 7:04:27 PM12/16/08
to django...@googlegroups.com
I encountered a scenario where I need to query the database for a
list of names sorted by length. In SQL this is easy:

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?

Russell Keith-Magee

unread,
Dec 16, 2008, 7:22:04 PM12/16/08
to django...@googlegroups.com

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

David Lindquist

unread,
Dec 16, 2008, 9:00:44 PM12/16/08
to Django users
Perfect. Exactly what I needed.

Thank you Russ

On Dec 16, 5:22 pm, "Russell Keith-Magee" <freakboy3...@gmail.com>
wrote:
> On Wed, Dec 17, 2008 at 9:04 AM, David Lindquist
>
> <david.lindqu...@gmail.com> wrote:
>
> > I encountered a scenario where I need to query the database for a
> > list of names sorted by length. In SQL this is easy:
>
> > 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('lengt h')
Reply all
Reply to author
Forward
0 new messages