Thursday, September 30, 2010

QuerySet values + annotate + order_by

The background here is that I am trying to modify django-voting to
sort the objects by score, but this is a general question.

The following code works minus the order_by statement on the end:

queryset = self.filter(
object_id__in = object_ids,
content_type = ctype,
).values(
'object_id',
).annotate(
score = CoalesceSum('vote', default='0'),
num_votes = CoalesceCount('vote', default='0'),
).order_by('score')

Without the order_by statement, I get the following result:

[{'score': 1, 'object_id': 2, 'num_votes': 1}, {'score': -1,
'object_id': 3, 'num_votes': 1}, {'score': 1, 'object_id': 4,
'num_votes': 1}]

but when adding order_by, I get the following error:

FieldError: Cannot resolve keyword 'score' into field. Choices are:
content_type
, id, object_id, user, vote

The choices listed belong to the "Vote" model. But why aren't the
available choices 'object_id' (from the values statement) and 'score'
and 'num_votes' (from the annotate statement)? I thought you could do
an order by anything in an annotate statement.

Thanks,
Scott

--
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+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment