I'm trying to add additional data to an aggregated query, like so:
(there are many MyModels for any date, and I want to sum up
MyModel.value for every single date, and then do a calculation on that
sum)

  qs = MyModel.objects.values('date').annotate(count=Sum('value'))
  for item in qs:
      item['kilocount'] = item['count'] / 1000

Now, it sounds reasonable to do that directly in the database:

 
MyModel.objects.values('date').annotate(count=Sum('value')).extra(select={'kilocount':
'"count" / 1000'))

According to the docs and my tests, .values() discards all .extra()
queries:

"If you use a values() clause after an extra() call, any fields
defined by a select argument in the extra() must be explicitly
included in the values() call. Any extra() call made after a values()
call will have its extra selected fields ignored."

If I try to fix this as proposed in the last paragraph, I end up with
the following:

  MyModel.objects.extra(select={'kilocount': '"count" /
1000')).values('date', 'kilocount').annotate(count=Sum('value'))

which in turn raises a DatabaseError("misuse of aggregate: SUM()")
from an erroneous SQL query (in the GROUP BY part):

  SELECT ("count" / 1000) AS "kilocount", "mymodel"."date",
SUM("mymodel"."value") AS "count" FROM "mymodel" GROUP BY
"mymodel"."date", "mymodel"."date", ("count" / 1000)

Is there no way to do this through the ORM on the database?
(Another solution would probably be a custom template filter, but that
doesn't strike me as too idiomatic.)

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