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

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to