提高django数据库查询的性能

时间:2011-12-28 07:09:20

标签: python django performance sqlite

我正在使用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分钟运行一次查询并保持缓存,这也是可以接受的,因为数据可能会稍微陈旧而没有不良影响

4 个答案:

答案 0 :(得分:7)

如果caching可以接受,则应始终使用它。类似的东西:

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

答案 1 :(得分:3)

Johnny Cache! http://packages.python.org/johnny-cache/ 它开箱即用,效果很好!

答案 2 :(得分:2)

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

答案 3 :(得分:-1)

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

相关问题