user9322651
user9322651

Reputation:

Speed up Django query

I am working with Django to create a dashboard which present many kind of data. My problem is that the page loading slowly despite I hit the database (PostgreSql) always once. These tables are loading with data in every 10th minute, so currently consist of millions of record. My problem is that when I make a query with Django ORM, I get the data slowly (according to the Django toolbar it is 1,4 second). I know that this not too much b is the half of the total loading time (3,1), so If I could decrease the time of the query the page loading could decrease to there for the user experience could be better. When the query run I fetch ~ 2800 rows. Is there any way to speed up this query? I do not know that I do something wrong or this time is normal with this amount of data. I attach my query and model. Thank you in advance for your help.

My query (Here I fetch 6 hours time intervall.):

  my_query=MyTable.filter(time_stamp__range=(before_now,  now)).values('time_stamp',  'value1', 'value2')

Here I tried to use .iterator() but the query wasn't faster.

My model:

class MyTable(models.Model):
        time_stamp = models.DateTimeField()
        value1 = models.FloatField(blank=True, null=True)
        values2 = models.FloatField(blank=True, null=True)

Upvotes: 2

Views: 1168

Answers (1)

Max Malysh
Max Malysh

Reputation: 31545

Add an index:

class MyTable(models.Model):
    time_stamp = models.DateTimeField()
    value1 = models.FloatField(blank=True, null=True)
    values2 = models.FloatField(blank=True, null=True)

    class Meta:
         indexes = [
             models.Index(fields=['time_stamp']),
         ]

Don't forget to run manage.py makemigrations and manage.py migrate after this.

Upvotes: 3

Related Questions