在lis上的Django lte/gte查询

2024-09-30 05:18:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下类型的数据:

数据被分割成“帧”,每个帧有一个开始和停止“gpstime”。在每一帧内是一组具有“gpstime”值的点。在

有一个frames模型,它有一个frame_名称、start_gps、stop_gps、,。。。在

假设我有一个gpstime值的列表,并希望找到每个值对应的frame_名称。在

我可以做一个循环。。。在

framenames = [frames.objects.filter(start_gps__lte=gpstime[idx],stop_gps__gte=gpstime[idx]).values_list('frame_name',flat=True) for idx in range(len(gpstime))]

这会给我一个'框架名称'的列表,每个gpstime一个。这就是我想要的。然而,这是非常缓慢的。在

我想知道的是:有没有更好的方法来执行这种查找,以便为每个gpstime获取一个比遍历列表更有效的framename。这个名单可能会变得非常庞大。在

谢谢!在

编辑:框架模型

^{pr2}$

Tags: 数据模型名称框架类型列表framesobjects
3条回答

如果我理解正确的话,gpstime是一个时间列表,您需要生成一个framename列表,其中每个gpstime都有一个。您当前的方法确实非常慢,因为它对每个时间戳进行db查询。你需要最小化数据库的点击数。在

我首先想到的答案是纽比。请注意,我在这里没有做任何额外的假设。如果你的gpstime列表可以排序,也就是说,排序并不重要,那么它可以更快地完成。在

试试这样的方法:

^{1}$

编辑: 由于列表已排序,因此可以使用.searchsorted()

^{pr2}$

加快速度的最佳方法是向这些字段添加索引:

^{1}$

然后运行manage.py dbsync。在

The frames table is very large, but I have another value that lowers the frames searched in this case to under 50. There is not really a pattern, each frame starts at the same gpstime the previous stops.

我不太明白您是如何将搜索的帧数减少到50,但是如果您只在50frames中搜索10000个gpstime值,那么将这50个帧加载到RAM中并用Python进行搜索,使用类似于foobarke的答案的方法。在

但是,如果您在整个表中搜索10gpstime值,比如说,10000000frames,那么您可能不想将所有10000000帧都加载到RAM中。在

您可以通过添加以下索引让数据库执行类似的操作。。。在

^{1}$

…然后使用这样的查询。。。在

^{pr2}$

…返回。。。在

+      +
| frame_name |
+      +
| Frame 2    |
| Frame 4    |
| Frame 7    |
+      +

…并且一个EXPLAIN显示了。。。在

+  +       +       +   -+       -+    +    -+   +   +             +
| id | select_type  | table        | type  | possible_keys | key    | key_len | ref  | rows | Extra                    |
+  +       +       +   -+       -+    +    -+   +   +             +
|  1 | PRIMARY      | myapp_frames | range | my_key        | my_key | 8       | NULL |    3 | Using where; Using index |
|  2 | UNION        | myapp_frames | range | my_key        | my_key | 8       | NULL |    5 | Using where; Using index |
|  3 | UNION        | myapp_frames | range | my_key        | my_key | 8       | NULL |    8 | Using where; Using index |
| NULL | UNION RESULT | <union1,2,3> | ALL   | NULL          | NULL   | NULL    | NULL | NULL |                          |
+  +       +       +   -+       -+    +    -+   +   +             +

…因此,您可以在一个查询中执行所有查询,该查询会命中该索引,并且该索引应缓存在RAM中。在

相关问题 更多 >

    热门问题