繁体   English   中英

提高django数据库查询的性能

[英]Improving performance of django DB query

我正在使用django / apache / sqlite3,我有一个看起来像这样的django模型:

class Temp_entry(models.Model):
    dateTime = models.IntegerField() #datetime
    sensor = models.IntegerField()   # id of sensor
    temp = models.IntegerField()     # temp as temp in Kelvin * 100

我正在尝试将最后300个Temp_entry项目放入图表中。 我这样做:

revOutsideTempHistory = Temp_entry.objects.filter(sensor=49).order_by('dateTime').reverse()[:300]

但是,此查询需要大约1秒钟。 有没有办法改善这个? 我挖了一遍,发现order_by效率很低,所以我希望有一个可行的选择吗?

我想到的一个替代方案,但无法弄清楚如何实现,将是每20分钟运行一次查询并保持缓存,这也是可以接受的,因为数据可能稍微陈旧而没有不良影响。

如果缓存是可接受的,则应始终使用它。 就像是:

from django.core.cache import cache

cached = cache.get('temp_entries')
if cached:
    result = cached 
else:
    result = Temp_entry.objects.filter(sensor=49).order_by('dateTime').reverse().values_list()[:300]
    cache.set('temp_entries', result, 60*20)  # 20 min

您还可以为相应的列设置db_indexes

class Temp_entry(models.Model):
    dateTime = models.IntegerField(db_index=True) #datetime
    sensor = models.IntegerField(db_index=True)   # id of sensor
    temp = models.IntegerField()     # temp as temp in Kelvin * 100

约翰尼卡什! http://packages.python.org/johnny-cache/它开箱即用,效果很好!

您可能需要在数据库中添加更多索引。 使用django-debug工具栏获取正在运行的实际查询的SQL,并使用EXPLAIN功能显示它正在使用的索引。 对于这个特定的查询,我想你需要在(sensor, dateTime)上添加索引 - 直接在数据库shell中执行。

好吧,如果你知道你的条目总是有一个增加的dateTime(即在创建条目时没有编辑时设置dateTime),那么你不必按dateTime排序,因为它们在数据库中自然会按顺序排列。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM