0

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?

4

1 回答 1

2

这应该有效:

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

查看从该查询生成的 SQL 表明它确实对舍入值进行了 GROUP BY。

于 2010-05-17T18:51:54.957 回答