使用距离查找进行Geodjango查询

时间:2017-12-11 08:19:53

标签: python geodjango

我想根据geodjango查询中计算的距离对结果进行排序 我尝试了两种方法,但是它们会抛出错误。

models.py

class Partner(models.Model):
 name = models.CharField(max_length=255)
 address = models.CharField(max_length=255)
 location = models.PointField(u"longitude/latitude",geography=True, blank=True, null=True)

views.py

方法1:

testing = Partner.objects.filter(location__distance_lte=(pnt, D(km=40))).annotate(distance=Distance('location', pnt)).order_by('distance')
print(testing)

错误:

Internal Server Error: /partner/filter/
Traceback (most recent call last):
 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner
 response = get_response(request)
 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response
 response = self.process_exception_by_middleware(e, request)
 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response
 response = wrapped_callback(request, *callback_args, **callback_kwargs)
 File "/home/prasanna/Projects/partner_server/partner/views.py", line 79, in Filter_function
 print(testing.annotate(distance=Distance('location', pnt)).order_by('distance'))
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

方法2:

testing = Partner.objects.filter(location__distance_lte=(pnt, D(km=40))).annotate(distance=Distance('location', pnt)).order_by('distance')
print(testing)

错误:

Internal Server Error: /partner/filter/
Traceback (most recent call last):
 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner
 response = get_response(request)
 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response
 response = self.process_exception_by_middleware(e, request)
 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response
 response = wrapped_callback(request, *callback_args, **callback_kwargs)
 File "/home/prasanna/Projects/partner_server/partner/views.py", line 79, in Filter_function
 print(testing.distance(pnt).order_by('distance'))
AttributeError: 'QuerySet' object has no attribute 'distance'

1 个答案:

答案 0 :(得分:0)

您的查询是正确的,但我认为您错过了某些内容,或者您​​在两种类型的Distance之间混合使用,第一种用法与第二种用法不同。

这是一个测量对象 1- from django.contrib.gis.measure import Distance

这是地理数据库功能之一 2-from django.contrib.gis.db.models.functions import Distance

第二个函数将以注释函数可以理解的比较方式迭代每个对象(以db为单位的行),但是第一个函数只是一个基本的测量函数,不能迭代或充当比较函数

您可以参考Django文档并查看差异

测量值:https://docs.djangoproject.com/en/2.1/ref/contrib/gis/measure/

数据库功能:https://docs.djangoproject.com/en/2.1/ref/contrib/gis/functions/#django.contrib.gis.db.models.functions.Distance