gpt4 book ai didi

python - Django 数据库查询很慢

转载 作者:行者123 更新时间:2023-11-29 03:32:22 24 4
gpt4 key购买 nike

我一直遇到 Django 选择的性能问题,我认为是中型查询。

这里是直接在Mysql中运行django查询的例子;

SELECT * FROM `website_datapoolposition` WHERE (`website_datapoolposition`.`data_pool_id` = 596 AND `website_datapoolposition`.`timestamp` <= '2015-01-24 23:31:33' AND `website_datapoolposition`.`timestamp` >= '2015-01-24 19:01:30');

集合中有 8063 行(0.05 秒)

我觉得这很合理。此表中有约 700 万行,时间戳已编入索引。

然而,当 django 将此数据作为值拉入时,需要 0.7 秒。 django 是否应该为原始 sql 添加 14 倍的开销?我用谷歌搜索了我能找到的每一个技巧,似乎没有什么能让我像我期望的那样降低到 ~80 毫秒。

编辑:

这是这个表的 django def:

#define my models
id = models.AutoField(primary_key=True)
car = models.ForeignKey(Car)
lat = models.DecimalField( max_digits=16, decimal_places=12 )
lng = models.DecimalField( max_digits=16, decimal_places=12 )
speed = models.DecimalField( max_digits=5, decimal_places=2, default=0 )
total = models.DecimalField( max_digits=12, decimal_places=2, null=True, blank=True)
dist = models.DecimalField( max_digits=12, decimal_places=2, null=True, blank=True)
timestamp = models.DateTimeField( db_index=True )

这是来自 show create table 的模式:

app_pos | CREATE TABLE `app_pos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lat` decimal(16,12) NOT NULL,
`lng` decimal(16,12) NOT NULL,
`speed` decimal(5,2) NOT NULL,
`timestamp` datetime NOT NULL,
`car_id` int(11) NOT NULL,
`total` decimal(12,2) DEFAULT NULL,
`dist` decimal(12,2),
PRIMARY KEY (`id`),
KEY `app_pos_fa16e375` (`car_id`),
KEY `app_pos_timestamp_f13fe0c76a90341_uniq` (`timestamp`),
KEY `app_pos_timestamp_343244cae95f1483_uniq` (`timestamp`),
CONSTRAINT `app_dat_car_id_feb2a18963295a287_fk_app_car_id` FOREIGN KEY (`car_id`) REFERENCES `app_car` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7000000 DEFAULT CHARSET=utf8

最佳答案

当你在 MySQL cli 中运行这个查询时,你会得到在服务器上执行查询的时间,而不是将行传输到另一个进程(甚至机器)并从这些行构建 8K 重对象的时间。

从 SQL 获取数据最快的 django 方式是:

data = DataPoolPosition.objects.filter(...).values_list('field1', 'field2')

您将获得迭代器,其中每一行都将由元组表示。

另一种选择是 execute custom SQL直接,但我不认为你会比 values_list() 选项有很大的速度提升。

关于python - Django 数据库查询很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28709578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com