首页 > 解决方案 > 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)

标签: djangodjango-querysetdjango-ormsqlperformance

解决方案


添加索引

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

不要忘记运行manage.py makemigrationsmanage.py migrate在此之后。


推荐阅读