从Django Querys获取值列表的最有效方法

2024-05-06 05:24:02 发布

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

我可以看到很多不同的选择,并希望对最有效或“最佳实践”方法的一些反馈。

我得到一个带filter()的Django Queryset

c_layer_points = models.layer_points.objects.filter(location_id=c_location.pk,season_id=c_season.pk,line_path_id=c_line_path.pk,radar_id=c_radar.pk,layer_id__in=c_layer_pks,gps_time__gte=start_gps,gps_time__lte=stop_gps)

这个查询集可能非常大(成百上千行)。

现在需要进行的是列表转换和JSON编码。

选项(我在搜索中看到过):

  1. 在queryset上循环

示例:

gps_time = [lp.gps_time for lp in c_layer_points];
twtt = [lp.twtt for lp in c_layer_points];
  1. 使用values()或values_list()
  2. 使用迭代器()

最后,我想将其编码为json格式,如下所示:

{'gps_time':[list of all gps times],'twtt',[list of all twtt]}

任何关于最好的方法的提示都是很好的,谢谢!


Tags: 方法inlayeridtimelinelocationfilter
2条回答

我建议您使用遍历查询集的方法,并从query set中逐个元素地确认json字典元素。

通常,Django的queryset是惰性的,这意味着它们在被访问时都会被加载到内存中。如果加载整个列表:gps_time = [lp.gps_time for lp in c_layer_points],那么所有这些对象都将在内存中(以千计)。你只需要做一个简单的迭代:

for item in c_layer_points:
    #convert item to json and add it to the
    #json dict.

另外,在python中,不需要在行尾使用;字符:)

希望这有帮助!

您可能无法从ORM中获取所需的格式。但是,您可以高效地执行以下操作:

c_layer_points = models.layer_points.objects.filter(location_id=c_location.pk, season_id=c_season.pk, line_path_id=c_line_path.pk,radar_id=c_radar.pk, layer_id__in=c_layer_pks, gps_time__gte=start_gps, gps_time__lte=stop_gps).values_list('gps_time', 'twtt')

现在把元组分成两个列表:(元组解包)

split_lst = zip(*c_layer_points)    
dict(gps_time=list(split_lst[0]), twtt=list(split_lst[1]))

相关问题 更多 >