2

I have a Django query which running well but I the execution slower than I make this same query in terminal. In curiosity I have run the django query (i have read it from Django Debug Tooltbar) in terminal and I got the same slow query. I tried to find out what could be the problem and I suspect to the ::timestamp conversion.

I try to present my problem below:

My django query:

   query=Table.filter(time_stamp__range=('2017-05-28 01:00:00',  '2017-05-28 07:00:00')).values('time_stamp',  'value')

Which is equalt to this raw sql statment according to Django Debug Toolbar:

SELECT * FROM "table" WHERE "table"."time_stamp" BETWEEN '2018-05-28T01:00:00.004325'::timestamp AND '2018-05-28T07:00:00.004325'::timestamp

Based on the Debug Toolbar result I got 1436,11 ms running time.

After that I logged in into my PostgreSQl database via terminal and I used this query:

select * from table where time_stamp between '2018-05-28 01:00:00' and '2018-05-28 07:00:00';

Here I got 753.086 ms execiton time.

The sample of my model:

class Table(models.Model):
    time_stamp = models.DateTimeField()
    value = models.FloatField(blank=True, null=True)

In my mind the two query is the same except the timestamp (::timestamp) conversation in Django query.

How could I avoid the the timestamp conversation in my Django query which I think coused the slow query? Thank you in advace for your help!

1 Answers1

2

There is overhead involved with using django's ORM, which converts records into objects. It will (almost?) always be slower than raw SQL.

If you only need the data and not an instance of your Table model, you can query the database directly.

warpri81
  • 571
  • 2
  • 6