python - 提高 django 数据库查询的性能

标签 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 分钟运行一次查询并将其缓存起来,这也是可以接受的,因为数据可能会稍微陈旧而不会产生不良影响.

最佳答案

如果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

关于python - 提高 django 数据库查询的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8652950/

相关文章:

python - 合并两个 pandas 数据框并跳过右侧的公共(public)列

MySQL在N个项目表中进行1对1连接

django - 如何在嵌套文件夹结构中引用我的模型以在 Django 3.2 中转储数据?

mysql - 有效地更新 mySQL 表?

MySQL慢查询不规律地飙升

来自对象字段的 Python 字典

python - 为什么类对象中的 tf.Variable 初始化失败?

python - 如何使 scrapy 输出信息在 debian 中显示与在 Windows 中相同的 cjk 外观?

Django外键表单保存

django - django rest框架的客户端?