django - 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)
解决方案
添加索引:
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 makemigrations
并manage.py migrate
在此之后。
推荐阅读
- google-apps-script - 谷歌表格存档和清除问题
- java - Hive UDF:通用 UDF 无法从嵌套映射访问结构
- docusignapi - 通过您的应用程序使用签名时,如何通过电子邮件发送签名请求?
- javascript - Javascript Popup 无法显示列表项
- javascript - 为什么我的代码没有在输入字段中添加数字(HTML/Javascript - 初学者)?
- flutter - Flutter,如何在没有 Twilio SDK 的情况下使用 Twilio 发送消息
- javascript - 在 JavaScript 中将图像和文本链接添加到同一个 html div 容器
- c# - 从一个视图切换到另一个视图时,如何保持用户控件的 Textbox Text 属性的值?
- terminal - 如何更改我的超级终端(从 hyper.is 下载)的主题?
- avr - 使用 Atmega32 读取 AVR 中打开 LED 的按钮状态