values_list of ordered annotated QuerySet

1,513 views
Skip to first unread message

Andreas Pfrengle

unread,
Mar 18, 2011, 2:09:56 PM3/18/11
to Django users
Hello,

I want to annotate a Queryset, order it by the annotated field and
then return a simple (ordered) values_list of the ids of the objects:

Wizard.objects.filter(**filterargs).annotate(wpower=Sum('creatures__power')).order_by('-
wpower').values_list('id', flat=True)

The 'Creature'-Model has a foreign key to 'Wizard' with
related_name='creatures', and it has a 'power'-IntegerField.
However, I get a 'FieldError: Cannot resolve keyword 'wpower' into
field

The only way that works is:
[w.id for w in
Wizard.objects.filter(**filterargs).annotate(wpower=Sum('creatures__power')).order_by('-
wpower')]
or
[w.id for w in
Wizard.objects.filter(**filterargs).annotate(wpower=Sum('creatures__power')).order_by('-
wpower').iterator()]

However, this takes more from the db than what I actually want. Any
ideas how I can achieve what I want with minimal db-load?

Andreas Pfrengle

unread,
Mar 22, 2011, 4:25:18 PM3/22/11
to Django users
just pulling it up again...

Marcos Moyano

unread,
Mar 22, 2011, 4:42:07 PM3/22/11
to django...@googlegroups.com, Andreas Pfrengle
This should work without grabbing the entire table:

[x[0] for x in Wizard.objects.filter(**filterargs).annotate(wpower=Sum('creatures__power')).order_by('- wpower').values_list('id', 'wpower')]

Rgds,
Marcos

On Tue, Mar 22, 2011 at 5:25 PM, Andreas Pfrengle <a.pfr...@gmail.com> wrote:
just pulling it up again...

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




--
Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.

Jamie Zawinski, in comp.emacs.xemacs

Andreas Pfrengle

unread,
Mar 22, 2011, 5:29:05 PM3/22/11
to Django users
Thank you, it works! :-)
Reply all
Reply to author
Forward
0 new messages