3

我可以看到很多不同的选项来执行此操作,并希望获得有关最有效或“最佳实践”方法的一些反馈。

我得到一个带有 filter() 的 Django 查询集

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. 循环查询集

例子:

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]}

任何有关执行此操作的最佳方法的提示都会很棒,谢谢!

4

2 回答 2

5

您可能无法从 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]))
于 2013-06-07T20:36:09.560 回答
2

我建议您使用遍历查询集并从查询集中逐个元素地符合 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 中行尾的字符:)

希望这可以帮助!

于 2013-06-07T20:18:57.357 回答