0

My aim is to create a query which calculate the absolute value of my field and calculate the average of them as well. I have read about it and I tarted to use the .extra possibility in Django but I couldn't achieve my goals. I attach my attempt ant the desired SQl query too. Thank you in advance.

The desired result would be equeal the reult of this PosreSql query:

SELECT
  time_stamp,
  AVG(ABS(ddt))
FROM tropo
WHERE time_stamp BETWEEN '2018-01-16 8:00' AND '2018-01-17 8:00'
GROUP BY time_stamp

My attempt is in Django:

Table.objects.all().filter(time_stamp__range=(2018-01-16 8:00, 2018-01-17 8:00))
.extra(select={"field_abs": "abs(field)"})
.values('time_stamp')
.annotate(avg_field=Avg('field_abs'))

How can I reach that my Djanogo query works?

1 Answers1

1

I don`t think you really need extra query here, try this:

from django.db.models import Func, Avg

tables = Table.objects.filter(time_stamp__range=(2018-01-16 8:00, 2018-01-17 8:00))
tables = tables.values('time_stamp').annotate(avg_field=Avg(Func('field', function='ABS')))
Basalex
  • 1,147
  • 9
  • 20
  • 1
    +1 avoiding using extra is extra cool! More about power of `Func` one can find here https://docs.djangoproject.com/en/2.0/ref/models/database-functions/ and what can be fired when using `postgresql` is listed here https://www.postgresql.org/docs/9.6/static/functions.html – andilabs Feb 06 '18 at 21:42
  • 1
    Thank you @Basalex, you suggested answer is worked fine for me. It was very useful for me! –  Feb 07 '18 at 07:10