Django query - “case when” with aggregation function

I have the following django model (mapped to table 'A'):

class A(models.Model):
    name = models.CharField(max_length=64, null=False)
    value = models.IntegerField()
    ...

I want to perform the following simple query on top:

select avg(case 
        when (value > 0 and value <= 50) then 0 
        when (value > 50 and value < 70) then 50 
        else 100 end) 
from A
where ...

I'm trying to avoid raw SQL - How can this be implemented with django (in the above example I'm using avg, but the same question is also relevant for max, min, sum etc.)?

I tried using extra and aggregate:

extra(select={'avg_field': case_when_query})

and

aggregate(Avg('avg_field')), 

but the aggregate function only works with model fields so the extra field cannot be used here. Как это можно сделать с помощью django?

Спасибо за помощь

9
задан Manoj Govindan 27 September 2010 в 05:47
поделиться