【发布时间】:2020-04-29 16:42:39
【问题描述】:
我通过上下文发送的查询如下:
context = {
'locations' = TravelData.objects.exclude(Q(from_lat__isnull=True) | Q(from_long__isnull=True) | Q(to_lat__isnull=True) | Q(to_long__isnull=True)).values('from_lat', 'from_long', 'to_lat', 'to_long')
}
这里有多个值(from_lat 和 from_long)和(to_lat 和 to_long)。我想只添加一次类似的值,即我必须同时检查 from 值和 to 值,如果存在则排除。
在前端,我在地图上渲染这些位置,点的坐标将是
[from_long, from_lat] or [to_long, to_lat]
如何更改上述查询以获得最有效的查询集?
编辑:
这是查询集的示例:
<QuerySet [{'to_lat': '52.92732', 'to_long': '77.63575', 'from_lat': '52.92415', 'from_long': '77.67229'}, {'to_lat': '52.92768', 'to_long': '77.62664', 'from_lat': '52.96691', 'from_long': '77.74935'}, {'to_lat': '53.047926', 'to_long': '77.597766', 'from_lat': '52.937222', 'from_long': '77.626915'}, {'to_lat': '52.97143', 'to_long': '77.63914', 'from_lat': '52.98999', 'from_long': '77.55332'}, {'to_lat': '52.92732', 'to_long': '77.63575', 'from_lat': '52.92415', 'from_long': '77.67229'}, {'to_lat': '52.92768', 'to_long': '77.62664', 'from_lat': '52.96691', 'from_long': '77.74935'}, {'to_lat': '53.047926', 'to_long': '77.597766', 'from_lat': '52.937222', 'from_long': '77.626915'}, {'to_lat': '52.97143', 'to_long': '77.63914', 'from_lat': '52.98999', 'from_long': '77.55332'}, {'to_lat': '52.97143', 'to_long': '77.63914', 'from_lat': '58.98999', 'from_long': '80.55332'}]>
在html文件的<script>标签中有一段代码是这样的:
var locations_object = {
type: 'FeatureCollection',
features: [
{% for i in locations %}
{
type: 'Feature',
geometry: {
type: 'geojson',
coordinates: ["{{i.from_long}}", "{{i.from_lat}}"]
},
properties: {
title: 'from_locations',
description: 'from_locations'
}
},
{
type: 'Feature',
geometry: {
type: 'geojson',
coordinates: ["{{i.to_long}}", "{{i.to_lat}}"]
},
properties: {
title: 'to_locations',
description: 'to_locations'
}
},
{% endfor %}
]
};
所以这里具有相同坐标值的位置在数据库中重复多次,如上下文的locations 变量所示。但是在渲染地图时,我只需要它一次。因此,在上下文中的查询中,如果可能的话,我如何才能将 [to_lat, to_long] 对和 [from_lat, from_long] 对只取一次?例如:在context 的locations 中,前四个元素再次重复。所以我必须只考虑一次。然后在第九个元素中,to_lat 和to_long 被重复,因为它已经存在于前一个元素中。所以我必须排除它,但 from_lat 和 from_long 不存在于前面的元素中。我必须在第九个要素中只考虑这一点。对所有条件都类似。
【问题讨论】:
-
您能添加一些示例数据吗?您是否试图获得所有不同的
[from_long, from_lat]对和[to_long, to_lat]对?如果[from_long, from_lat]对两个 TravelData obj 相同,您想保留哪一对[to_long, to_lat]? -
我已对问题进行了编辑。请检查一下。
-
你能展示过滤后的查询集应该解决什么问题吗?或者你的最终值会是什么样子?看来您想要所有不同的
[from_long, from_lat]对所有不同的[to_long, to_lat]对? -
没错。我想要所有这些不同的对。
标签: django