【发布时间】:2017-09-07 23:54:12
【问题描述】:
我目前使用以下方法按距离对模型的结果进行排序:
views.py
SearchPoint = Point(long, lat)
res = Model.objects.filter(location__distance_lte=(SearchPoint, D(m=2000)))
.annotate(distance=Distance('location', SearchPoint))
.order_by('distance')
这允许我将 2000m 内的结果按distance 排序。
现在我还想显示SearchPoint 给出的搜索者与我的Model 的结果之间的距离。
Models.py 在我的模型类中,我定义了以下属性:
@property
def distance_to_searcher(self):
distance =self.location.distance(SearchPoint)
return distance * 100
但我收到以下错误:
名称“搜索点”未定义
我知道这没有定义,因为它是在 views.py 文件中定义的,这是一个 GET 请求,从 URL 中获取 long 和 lat 参数并将它们放入 Point() 类中。
理想情况下,我会将距离四舍五入到一个不错的数字。
编辑:我在 views.py
中定义了SearchPoint
def get_context_data(self, **kwargs):
if self.request.method == 'GET':
form = LocationForm(self.request.GET)
if form.is_valid():
SearchPoint=Point(form.cleaned_data['Lng'],form.cleaned_data['Lat'])
else:
form = LocationForm()
SearchPoint=Point(0,0)
【问题讨论】: