4

In Django 1.2.3 I need to perform a query like this:

SELECT FLOOR(quantity/100) FROM mytable

is there any way to make it in pure Django style?

Then, a more difficult step:

SELECT FLOOR(quantity/100), count(*) 
FROM mytable
GROUP BY FLOOR(quantity/100)

is there any standard solution?

Don
  • 16,928
  • 12
  • 63
  • 101

3 Answers3

3

You'll need to use SQL for this. Django's ORM is very useful as far as it goes, but you're stepping well out of the cases that it covers. I wouldn't even say that the raw() queryset method would help here - I would use the functionality to execute custom SQL directly.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
3

I ended up using the extra clause:

MyModel.objects.extra(group='FLOOR(quantity/100)')\
    .values('group')\
    .annotate(count=Sum('quantity'))\
    .order_by()

the argument of Sum is quite misterious, but it works...

Don
  • 16,928
  • 12
  • 63
  • 101
  • 1
    Be careful using functions that are database vendor dependent. You can achieve the same result by doing the computation within Django, while remaining database agnostic. You may trade performance for independence however. – Josh Smeaton Jan 17 '11 at 10:23
1

Starting from Django 2.2 you can use the Floor function:

class Floor(Transform):
    function = 'FLOOR'
    lookup_name = 'floor'
Dos
  • 2,250
  • 1
  • 29
  • 39