views:

26

answers:

1

Django 1.1.1

Models.py:

class Datapoint(models.Model):
    parameter1 = models.FloatField()
    parameter2 = models.FloatField()

I want to bin the values of parameter1 to the nearest integer (or other rounding), and then return the average of the two parameters for this bin.

In SQL I would do the following:

select round(parameter1,0),
    avg(parameter1),
    avg(parameter2)
from Datapoints
group by round(parameter1,0)
order by round(parameter1,0)

Can I achieve the same using aggregation on a queryset in a django view, or will it only group by fields directly?

Alternatively, is there a way to set the rounded value as a meta-field in the model and refer to this in the view?

+1  A: 

This should work:

from django.db.models import Avg
Datapoint.objects.extra(
    select={'rounded_param1': 'ROUND(parameter1)'}
).values('rounded_param1').annotate(Avg(parameter1)).annotate(Avg(parameter2))

A look at the SQL generated from that query shows that it does indeed GROUP BY on the rounded value.

Daniel Roseman
@Daniel Roseman: that works perfectly, thanks! - I was a bit confused by the official .extra() documentation
meepmeep