user9322651
user9322651

Reputation:

Make Django query with .extra

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?

Upvotes: 0

Views: 358

Answers (1)

Basalex
Basalex

Reputation: 1187

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')))

Upvotes: 1

Related Questions